简体   繁体   中英

Retrieve data from multi level inner list using java8 stream

I have List of Employee s , each employee has a list of Department s in it, each department has a list of location , I want to fetch the list of location based on some filter condition.

Here is my code -

for (Employee empl : employeeList) {
    if(empl.getEmployeeName().equals("XXX")) {
        for (Department dept : empl.getDepartmets()) {
            if(dept.getDepartmentName().equals("Sales")) {
                return dept.getLocations();
            }
        }
    }
}

I want to handle this on java8 steam api , can anyone help ?

employeeList.stream()
          .filter(x -> "XXX".equals(x.getEmployeeName()))
          .flatMap(x -> x.getDepartmets().stream().filter(y -> "Sales".equals(y.getDepartmentName())))
          .findFirst()
          .map(Department::getLocations)
          .orElse(Collections.emptyList());

The only point would be that flatMap is not really lazy until if you really care about this and I assume locations is a List of some type here.

  1. Create a Stream<Employee> from the employeeList
  2. filter this stream to retain only employees where their name is "XXX"
  3. map/flatten the Stream<Employee> into a Stream<Department>
  4. filter this list of departments to retain the item where the department name is equal to "Sales"
  5. get the find matching item with findFirst
  6. map to Department::getLocations which you can then get the value the Optional contains with calls to orElse providing a default value or ifPresent or whatever is sufficient in your use case.

Code:

   employeeList.stream()  // step 1
               .filter(e -> e.getEmployeeName().equals("XXX")) // step 2
               .flatMap(e -> e.getDepartmets().stream()) // step 3
               .filter(d -> "Sales".equals(d.getDepartmentName())) // step 4
               .findFirst() // step 5
               .map(Department::getLocations); // step 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM