jdk8 list.stream tomap()异常

当使用Java 8的Stream API的`toMap()`方法时,遇到`IllegalStateException: Duplicate key`异常。问题源于映射过程中出现重复的键。为解决此问题,可以改用`toMap(Function, Function, BinaryOperator)`,在键冲突时提供合并策略。示例代码中展示了如何在键冲突时保留第一个元素。" 115816649,10537228,Matlab 1MHz正弦波与2kHz锯齿波调制仿真,"['Matlab编程', '信号处理', '模拟信号', '调制仿真']
摘要由CSDN通过智能技术生成

异常标识:java.lang.IllegalStateException: Duplicate key 1;

 

代码如下:

Map<String,RuleNode> allMap=treeList.stream().collect(Collectors.toMap(RuleNode::getId, Function.identity());

 

错误原因:原因是存在重复key导致。

 

查看toMap文档: public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper) Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements. If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys may have duplicates, use toMap(Function, Function, BinaryOperator) instead. API Note: It is common for either the key or the value to be the input elements. In this case, the utility method F

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值