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 java-10 if you really care about this and I assume locations
is a List
of some type here.
Stream<Employee>
from the employeeList
filter
this stream to retain only employees where their name is "XXX" Stream<Employee>
into a Stream<Department>
"Sales"
findFirst
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.