这个问题在这里已有答案:
我是Java8的新手。我需要按照特定条件将POJO列表转换为组,并在UI上显示。
Children.java
private String firstName;
private String lastName;
private String school;
private String personId;
// Setters and getters.
Person.java
private String fullName;
private String address;
// Setters and Getters.
private Person convertChildToPerson(Children child) {
Person person = new Person();
person.setFullName(child.getLastName() + ", " + child.getFirstName());
..
return person;
}
..主要代码.. ..
List<Person> personList; // Is populated by other functions.
// Connect to DB and gets the output
List<Children> childrenList = (Children) criteria.list();
for(Children children: childrenList) {
personList.add(convertChildToPerson(children));
}
return personList;
上面的FOR-LOOP不能被Java 8 Streams取代吗? List<Person> newList = childrenList.stream()
.map(this::convertChildToPerson)
.collect(Collectors.toList());
personList.addAll(newList);
如Holger所建议的那样更短(更好):
childrenList.stream()
.map(this::convertChildToPerson)
.forEachOrdered(personList::add);