HItesh Thakkar
HItesh Thakkar

Reputation: 1

How to return List of Object using Stream API

My EmployeeDeatils Object has List of other object inside (employeeData). I am trying to fetch that with some mapping with id

But not sure what I am doing wrong

     private List<EmployeeData> getEmployeeMessage(List<EmployeeDetails> employeeDetailList, Employee employee) {

    return employeeDetailList.stream()
        .filter(employeeDetail -> employeeDetail.getEmployeeId() == employee.getEmployeeId())
        .map(employeeDetail -> employeeDetail.getEmployeeData())
        .collect(Collectors.toList);

}

Upvotes: 0

Views: 50

Answers (1)

Tasos P.
Tasos P.

Reputation: 4114

Assuming that your EmployeeDetails class has List<EmployeeData> getEmployeeData() field, you can fetch these using:

List<EmployeeData> getEmployeeMessage(List<EmployeeDetails> employeeDetailList, Employee employee) {

        return employeeDetailList.stream()
                .filter(employeeDetail -> employeeDetail.getEmployeeId() == employee.getEmployeeId())
                .flatMap(employeeDetail -> employeeDetail.getEmployeeData().stream())
                .collect(Collectors.toList());

    }

As @Naman correctly pointed out, you need to pay attention on flatMap vs map operations.

In this case, a flatMap is used because you need a mapping operation for each element of your list (returned by getEmployeeData()).

Upvotes: 1

Related Questions