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?
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With