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

使用Collectors.toMap转换Rule集合为Map报Duplicate key错如何解决

修复方案

错误原因

你使用的无合并策略的Collectors.toMap()方法默认不允许键重复,当集合中出现相同id的元素时,没有对应的冲突处理逻辑,就会抛出IllegalStateException异常。

修复方法

调用带合并策略参数的Collectors.toMap重载方法,第三个参数就是重复键时的值处理函数,你可以根据业务需求选择对应的策略:

  • 保留先出现的值,丢弃后续重复键的新值
Map<Integer, Long> map = ruleList.stream()
        .collect(Collectors.toMap(
                Rule::getId,
                Rule::getCableType,
                (oldValue, newValue) -> oldValue
        ));
  • 保留后出现的值,覆盖之前重复键的旧值
Map<Integer, Long> map = ruleList.stream()
        .collect(Collectors.toMap(
                Rule::getId,
                Rule::getCableType,
                (oldValue, newValue) -> newValue
        ));
  • 相同id的数值做聚合计算,比如求和
Map<Integer, Long> map = ruleList.stream()
        .collect(Collectors.toMap(
                Rule::getId,
                Rule::getCableType,
                Long::sum
        ));

如果还需要指定生成的Map实现类(比如要保留集合遍历顺序可以用LinkedHashMap),可以再加第四个构造函数参数:

Map<Integer, Long> map = ruleList.stream()
        .collect(Collectors.toMap(
                Rule::getId,
                Rule::getCableType,
                (oldValue, newValue) -> newValue,
                LinkedHashMap::new
        ));

注意:你需要先给Rule类补充对应的getId()、getCableType() getter方法,上述代码中的方法引用才能正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:21:03