这个问题在这里已经有了答案:
Create list of object from another using Java 8 Streams
(4 个回答)
4年前关闭。
我想使用流从类型 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;
}
目前,这段代码有效。但我想知道并想知道是否有更好的方法来创建
Person
的集合来自 Employee
不使用 forEach
.
最佳答案
这是一个更简洁的方法。在流中使用 .forEach() 表明可能有更好的方法来使用 Stream。流旨在具有功能性,并且它们试图远离可变性。
public static List<Person> createPersonsFromEmployees(List<Employee> employees)
Function<Employee, Person> employeeToPerson = e -> new Person(e.getFirstName, e.getLaseName(), e.getEmail());
return employees.stream()
.filter(Object :: nonNull)
.map(employeeToPerson)
.collect(Collectors.toList());
}
关于java 8流从类型A的集合创建类型B的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43315161/