How to apply Filtering on groupBy in java streams

You can make use of the Collectors.filtering API introduced since Java-9 for this:

Map<String, List<Employee>> 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 or partitioningBy.

  • A filtering collector differs from a stream’s filter() operation.

Leave a Comment