Reputation: 2368
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?
Upvotes: 5
Views: 6740
Reputation: 14829
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
.
Upvotes: 14