How do you group first and then apply filtering using Java streams?
Example: Consider this Employee
class:
I want to group by Departme
You can make use of the Collectors.filtering API introduced since Java-9 for this :
Map> output = list.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.filtering(e -> e.getSalary() > 2000, Collectors.toList())));
Important from the API note :
The filtering() collectors are most useful when used in a multi-level reduction, such as downstream of a
groupingBy
orpartitioningBy
.A filtering collector differs from a stream's
filter()
operation.