Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Stream to instantiate new objects

In java8, I got a Set of String:

final Set<String> nameSet = this.getNames();

And I want to get a list of People, setting the name of People based on the String from the Set. However, People class do not have a constructor like new People(name), it can only be implemented by using setName method.

In old way, I can do something like:

    List<People> peoples = new ArrayList<People>();
    for(String name: nameSet){
        People people = new People();
        people.setName(name);
        peoples.add(people);
    }

How could I use Stream to convert this?

like image 689
chrisTina Avatar asked Oct 09 '16 23:10

chrisTina


People also ask

What is stream () in Java?

A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

Can stream API be reused?

No. Java streams, once consumed, can not be reused by default. As Java docs say clearly, “A stream should be operated on (invoking an intermediate or terminal stream operation) only once.


1 Answers

If possible, it may be worth considering adding a People constructor that takes a name. Then you could do this:

List<People> peoples = nameSet.stream()
  .map(People::new)
  .collect(Collectors.toList());

If you can't add a constructor, you can either do it like this:

List<People> peoples = nameSet.stream()
  .map(name -> {
    People people = new People();
    people.setName(name);
    return people;
  }).collect(Collectors.toList());

Or better in my opinion:

List<People> peoples = nameSet.stream()
  .map(name -> createPeopleFromName(name))
  .collect(Collectors.toList());

And elsewhere in the code have this method, perhaps in a PeopleUtils class:

public static People createPeopleFromName(String name)
{
  People people = new People();
  people.setName(name);
  return people;
}

Maybe also consider renaming the class People to Person.

like image 97
clstrfsck Avatar answered Sep 28 '22 06:09

clstrfsck