How to apply Filtering on groupBy in java streams

后端 未结 5 851
孤城傲影
孤城傲影 2020-12-05 10:16

How do you group first and then apply filtering using Java streams?

Example: Consider this Employee class: I want to group by Departme

5条回答
  •  抹茶落季
    2020-12-05 10:30

    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 or partitioningBy.

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

提交回复
热议问题