使用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
相关产品推荐
相关产品推荐

