You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java Stream中应用双重过滤统计符合条件的部门数量

实现方案

你可以通过调整Stream的过滤、收集逻辑实现需求,有两种常用写法:

写法1:先过滤全量符合薪资要求的员工,再分组统计

这种写法会先排除所有薪资低于100的员工,再统计各部门剩余人数,最终筛选符合人数要求的部门计数,性能相对更高:

long qualifiedDeptNum = employees.stream()
    // 过滤出所有薪资不低于100的员工
    .filter(emp -> emp.getSalary() >= 100)
    // 按部门分组统计人数
    .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()))
    // 取所有部门的人数
    .values()
    .stream()
    // 筛选人数≥30的部门
    .filter(count -> count >= 30)
    // 统计符合要求的部门数量
    .count();

写法2:分组后再过滤各部门下符合要求的员工

如果需要保留所有部门的统计数据(哪怕薪资达标人数为0),可以用这种写法:

// 第一步:统计每个部门的薪资达标人数
Map<String, Long> deptQualifiedCount = employees.stream()
    .collect(Collectors.groupingBy(
        Employee::getDepartment,
        // 分组后只统计当前部门薪资≥100的员工数
        Collectors.filtering(emp -> emp.getSalary() >= 100, Collectors.counting())
    ));

// 第二步:筛选人数≥30的部门,统计数量
long qualifiedDeptNum = deptQualifiedCount.values().stream()
    .filter(count -> count >= 30)
    .count();

注意事项

你的Employee类中getter方法名拼写错误,getDeparment缺少字母t,正确应为getDepartment,否则方法引用会报错。

内容的提问来源于stack exchange,提问作者Tango12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 18:15:03