使用Stream实例化新对象

时间:2016-10-09 23:11:25

标签: java java-8 java-stream

java8中,我得到了一组字符串:

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

我希望获得People的列表,根据People中的字符串设置Set的名称。 但是,People类没有像new People(name)这样的构造函数,只能使用setName方法实现。

以旧方式,我可以做类似的事情:

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

我如何使用Stream转换此内容?

1 个答案:

答案 0 :(得分:5)

如果可能,可能值得考虑添加一个带有名称的People构造函数。然后你可以这样做:

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

如果你不能添加构造函数,你可以这样做:

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

或者在我看来更好:

List<People> 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;
}

也许还考虑将课程People重命名为Person