List<String> strings = Arrays.asList("3","55","3");
Map<String,Integer> map = strings
.stream()
.collect(Collectors.toMap(s ->s, s -> s.length()));
returns
java.lang.IllegalStateException: Duplicate key 1
where I would expect Duplicate key 3
If the mapped keys may have duplicates, use toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction) instead. So you should use toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction) instead.
Collectors.toMap() with Mapper and Merge FunctionsIt's input are two values that is the two values for which keyMapper returned the same key, and merges those two values into a single one.
This was fixed in Java 9. Now the error message is correct:
java.lang.IllegalStateException: Duplicate key 3 (attempted merging values 1 and 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With