The test also reported the bug.
To test the problem of small partners, said is an interface does not return data, well, although not I write the interface task fell to the end also have to solve, the local debugging a bit, good guy, directly thrown an anomaly out, this is the elder brother drunk write code ...
Exception in thread "main" java.lang.IllegalStateException: Duplicate key at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133) at java.util.HashMap.merge(HashMap.java:1254) at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320) at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169) at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
Key repeat exception resolution
The line code for the error is as follows:
Map<Long, Entity> entityMap= entityList.stream().collect(Collectors.toMap(Entity::getType, (entity) -> entity));
The purpose of this line of code is to convert a list object to a Map object, with type key and the entity object as value.
But with the usual method, but the direct use of Java8 stream way, the error is also very clear, is the key repetition, that is, when using the Tomap method, there is a duplicate type value caused the error, the final solution is as follows:
Map<Long, Entity> entityMap= entityList.stream().collect(Collectors.toMap(Entity::getType, Function.identity(),(entity1,entity2) -> entity1));
The overloaded method of using Tomap (), if it already exists, is no longer modified to avoid duplicate key issues.
By the way, this is already how long ago the code, how today only reported this mistake, is also drunk.
JDK8 Stream Tomap () java.lang.IllegalStateException:Duplicate key exception resolved (key repeat)