How do you group first and then apply filtering using Java streams?
Example: Consider this Employee class:
I want to group by Departme
There is no cleaner way of doing this in Java 8: Holger has shown clear approach in java8 here Accepted the Answer.
This is how I have done it in java 8:
Step: 1 Group by Department
Step: 2 loop throw each element and check if department has an employee with salary >2000
Step: 3 update the map copy values in new map based on noneMatch
Map> employeeMap = list.stream().collect(Collectors.groupingBy(Employee::getDepartment));
Map> newMap = new HashMap>();
employeeMap.forEach((k, v) -> {
if (v.stream().noneMatch(emp -> emp.getSalary() > 2000)) {
newMap.put(k, new ArrayList<>());
}else{
newMap.put(k, v);
}
});
Java 9 : Collectors.filtering
java 9 has added new collector Collectors.filtering this group first and then applies filtering. filtering Collector is designed to be used along with grouping.
The Collectors.Filtering takes a function for filtering the input elements and a collector to collect the filtered elements:
list.stream().collect(Collectors.groupingBy(Employee::getDepartment),
Collectors.filtering(e->e.getSalary()>2000,toList());