user974802
user974802

Reputation: 3457

How to return List with Streams in this case?

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

Upvotes: 2

Views: 134

Answers (3)

corroborator
corroborator

Reputation: 321

List<StudentVO> studentsList=hDtoList.stream().filter(hdto->hdto.getHouseName().equals("ZSRT")).findFirst().get().getStudents();

// studentsList may be null if not found

Upvotes: 1

pezetem
pezetem

Reputation: 2541

try the following with the use of flatMap

List<StudentVO> studentVOList = hDtoList.stream()
            .filter(h -> h.getHouseName().equals("ZSRT"))
            .flatMap(h -> h.getStudentVOList().stream())
            .collect(Collectors.toList());

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59988

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());

Upvotes: 4

Related Questions