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

如何用Java Stream提取对象中指定字段的去重值?

提取对象字段的去重值解决方案

方法一:直接通过Stream链实现(最简洁)

不需要先转换为Map,直接通过map提取字段、distinct去重,最后收集为列表:

List<Long> managerIds = employees.stream()
    .map(Employee::getManagerId)
    .distinct()
    .collect(Collectors.toList());
  • map(Employee::getManagerId):将每个Employee对象转换为对应的managerId字段值
  • distinct():对managerId进行去重
  • collect(Collectors.toList()):将去重后的结果收集为List<Long>

方法二:复用已有的Map实现

如果你已经因其他业务需求创建了employeeMap,可以直接通过Map的keySet()获取去重后的managerId,再转换为列表:

// 你已有的Map实现
Map<Long, Employee> employeeMap = employees.stream()
    .collect(Collectors.toMap(Employee::getManagerId, Function.identity(), (o, n) -> n));

// 转换为去重的managerId列表
List<Long> managerIds = new ArrayList<>(employeeMap.keySet());

因为toMap的key就是去重后的managerId(重复key会被新值覆盖,对应你传入的合并函数(o, n) -> n),所以keySet()天然就是去重后的字段集合。

内容的提问来源于stack exchange,提问作者αƞjiβ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:34:51