【问题标题】:Implementation of having count with group by in java 8在 java 8 中使用 group by 计数的实现
【发布时间】:2016-03-28 11:05:43
【问题描述】:
我正在寻找 group by 的实现,然后根据 lambda 表达式中的计数进行过滤。
select COUNT(employee_id), department_id from employee
GROUP BY department_id
HAVING COUNT(employee_id) > 1
有没有使用 lambda 表达式实现这一点的简单实现。
【问题讨论】:
标签:
java
lambda
java-8
java-stream
【解决方案1】:
您可以将groupingBy 收集器与counting() 和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; }));
请注意,这里不能保证 groupingBy 返回的映射的可变性,因此您可以使用重载版本并根据需要提供具体的可变实例。