我想使用流創建類型B的類型集合。java 8創建類型A集合中的類型B的集合
假設我有兩個班
Class Employee{
String firstName;
String lastName;
int age;
String id;
String email;
double salary;
}
Class Person {
String firstName;
String lastName;
String email;
}
從員工的集合創建人的集合,我寫下面的代碼
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
的集合。
感謝您的解釋。 – cmodha