Implementing a number with a group in java 8

I am looking for an implementation of the by group, having and then filtering based on count in lambda expressions.

select COUNT(employee_id), department_id from employee GROUP BY department_id HAVING COUNT(employee_id) > 1 

Is there any simple implementation to achieve this using lambda expressions.

+5
source share
1 answer

You can combine the groupingBy collector with counting() and collectingAndThen :

 import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.counting; import static java.util.stream.Collectors.groupingBy; ... Map<Long, Long> map = employees.stream() .collect(collectingAndThen(groupingBy(Employee::getDeptId, counting()), m -> { m.values().removeIf(v -> v <= 1L); return m; })); 

Please note that there is no guarantee on the volatility of the map returned by groupingBy , so you can use the overloaded version and provide a specific mutable instance if you want.

+6
source

Source: https://habr.com/ru/post/1245898/


All Articles