Implementation of counting using group in Java 8
•
Java
I am looking for the implementation of group by, and then filter it according to the count in the lambda expression
select COUNT(employee_id),department_id from employee GROUP BY department_id HAVING COUNT(employee_id) > 1
Is there a simple implementation of using lambda expressions for this purpose
Solution
You can use the groupingby collector with counting() and collectandthen:
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 the variability of the mapping returned by groupingby cannot be guaranteed here, so you can use the overloaded version and provide specific variable instances if necessary
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码