报错代码
myList.stream().collect(Collectors.toMap(MyDto::getCd, MyDto::getNm));
报错信息
java.lang.IllegalStateException: Duplicate key 000001-01-0000000000002-0001-0002 (attempted merging values 2000 and 2000)
at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:135)
at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:182)
at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682)
正确写法/稳妥写法
myList.stream().collect(Collectors.toMap(MyDto::getCd, MyDto::getNm, (v1, v2) -> v2)));
如果业务上,myList中的MyDto::getCd会拿到重复数据,就会导致Duplicate key错误产生。
所以需要指定重复key的处理规则。
(v1, v2) -> v1 :不覆盖
(v1, v2) -> v2 :直接覆盖旧的key