How to apply Filtering on groupBy in java streams

后端 未结 5 855
孤城傲影
孤城傲影 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:27

    Java 8 version: You can make grouping by Department and then stream the entry set and do the collect again with adding the predicate in filter:

        Map> collect = list.stream()
            .collect(Collectors.groupingBy(Employee::getDepartment)).entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getKey,
                entry -> entry.getValue()
                    .stream()
                    .filter(employee -> employee.getSalary() > 2000)
                    .collect(toList())
                )
            );
    

提交回复
热议问题