在java8中,我得到了一组字符串:
final Set nameSet = this.getNames();
我想得到一个People列表,根据Set中的String设置People的名称.
但是,People类没有像new People(name)这样的构造函数,它只能通过使用setName方法实现.
以旧方式,我可以做类似的事情:
List peoples = new ArrayList();
for(String name: nameSet){
People people = new People();
people.setName(name);
peoples.add(people);
}
我怎么能用Stream来转换呢?
解决方法:
如果可能的话,可能值得考虑添加一个带有名称的People构造函数.然后你可以这样做:
List peoples = nameSet.stream()
.map(People::new)
.collect(Collectors.toList());
如果你不能添加构造函数,你可以这样做:
List peoples = nameSet.stream()
.map(name -> {
People people = new People();
people.setName(name);
return people;
}).collect(Collectors.toList());
或者在我看来更好:
List peoples = nameSet.stream()
.map(name -> createPeopleFromName(name))
.collect(Collectors.toList());
代码中的其他地方有这个方法,也许在PeopleUtils类中:
public static People createPeopleFromName(String name)
{
People people = new People();
people.setName(name);
return people;
}
也许还考虑将Person to Personate重命名为Person.
标签:java,java-8,java-stream
来源: https://codeday.me/bug/20190828/1755748.html