【发布时间】:2017-04-10 04:47:12
【问题描述】:
我想使用流从类型 B 创建一个类型 A 的集合。
假设我有两个班级
Class Employee{
String firstName;
String lastName;
int age;
String id;
String email;
double salary;
}
Class Person {
String firstName;
String lastName;
String email;
}
为了从 Employee 集合创建 Person 集合,我编写了以下代码
public static List<Person> createPersonsFromEmployees(List<Employee> employees) {
List<Person> persons = new ArrayList<>();
employees.stream().filter(Object :: nonNull)
.forEach(e -> {
persons.add(new Person(e.getFirstName(),
e.getLastName(),
e.getEmail());
};)
return persons;
}
目前,这段代码有效。但我想知道是否有更好的方法可以在不使用forEach 的情况下从Employee 创建Person 的集合。
【问题讨论】:
标签: java collections java-8 java-stream