How to return List with Streams in this case?

user974802 :

I have this method

private List<StudentVO> getStudentVOList() {
    List<HouseDTO> hDtoList = new ArrayList<HouseDTO>();
    for (HouseDTO hdn : hDtoList) {
        if (hdn.getHouseName().equals("ZSRT")) {
            return hdn.getStudents();
        }
    }

which i am trying to convert to Java 8 , i have tried as shown below

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;
}
YCF_L :

You can use findAny or findFirst after the map then orElse(someDefaulValues), in your case an empty collection.

return  hDtoList.stream()
                .filter(hdn->hdn.getHouseName().equals("ZSRT"))
                .findFirst()
                .map(StudentVO::getStudents)
                .orElse(Collections.emptyList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116601&siteId=1