Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the error reporting in Collectors.toMap() broken? [duplicate]

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

like image 971
Paul Janssens Avatar asked Mar 29 '18 13:03

Paul Janssens


People also ask

How do I avoid duplicate keys in collectors toMap?

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.

What is Merge function in collectors toMap?

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.


1 Answers

This was fixed in Java 9. Now the error message is correct:

java.lang.IllegalStateException: Duplicate key 3 (attempted merging values 1 and 1)
like image 63
ZhekaKozlov Avatar answered Sep 28 '22 07:09

ZhekaKozlov