我有此方法
private List<StudentVO> getStudentVOList() {
List<HouseDTO> hDtoList = new ArrayList<HouseDTO>();
for (HouseDTO hdn : hDtoList) {
if (hdn.getHouseName().equals("ZSRT")) {
return hdn.getStudents();
}
}
我正尝试转换为Java 8,如下所示
return hDtoList.stream().filter(hdn->hdn.getHouseName().equals("ZSRT")).map(hdn->hdn.getStudents()).collect(Collectors.toList());
-
public class HouseDTO {
public String getHouseName() {
return houseName;
}
public void setHouseName(String houseName) {
this.houseName = houseName;
}
public List<StudentVO> getStudents() {
return students;
}
public void setStudents(List<StudentVO> students) {
this.students = students;
}
private String houseName ;
List<StudentVO> students;
}
public class StudentVO {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
private String name;
private int rollNo;
}
答案 0 :(得分:4)
您可以在findAny
之后使用findFirst
或map
,然后使用orElse(someDefaulValues)
,在您的情况下为空集合。
return hDtoList.stream()
.filter(hdn->hdn.getHouseName().equals("ZSRT"))
.findFirst()
.map(StudentVO::getStudents)
.orElse(Collections.emptyList());
答案 1 :(得分:1)
使用flatMap
List<StudentVO> studentVOList = hDtoList.stream()
.filter(h -> h.getHouseName().equals("ZSRT"))
.flatMap(h -> h.getStudentVOList().stream())
.collect(Collectors.toList());
答案 2 :(得分:1)
List<StudentVO> studentsList=hDtoList.stream().filter(hdto->hdto.getHouseName().equals("ZSRT")).findFirst().get().getStudents();
// studentsList may be null if not found