11
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

Mena
  • 47,782
  • 11
  • 87
  • 106
Paul Janssens
  • 622
  • 3
  • 9
  • 1
    Replicated with 1.8.0u152. It seems to log the `HashMap$Node`'s `value` instead of its `key`... – Mena Mar 29 '18 at 13:11
  • 1
    notice that if you do `Collectors.toMap(s ->s, s ->4)`, you get `java.lang.IllegalStateException: Duplicate key 4`, so it seems it is actually complaining about the value being duplicate – Bentaye Mar 29 '18 at 13:11
  • 5
    See https://bugs.openjdk.java.net/browse/JDK-8173464 – Zircon Mar 29 '18 at 13:12
  • @Zircon interestingly, the bug your link to is marked as duplicate for [8040892](https://bugs.openjdk.java.net/browse/JDK-8040892), which itself claims to be fixed. See also other duplicate [8178142](https://bugs.openjdk.java.net/browse/JDK-8178142). Mah. – Mena Mar 29 '18 at 13:14
  • 2
    @Mena and the duplicate reference shows "Fix Version/s: 9" - It was not fixed until Java 9. – Zircon Mar 29 '18 at 13:16
  • @Zircon ah yes :) Fair enough then... You could pack all that into an answer! – Mena Mar 29 '18 at 13:16

3 Answers3

2

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

java.lang.IllegalStateException: Duplicate key 3 (attempted merging values 1 and 1)
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
1

Seems, like this was a bug in JDK 8 but is no longer the case as of JDK 9. Reason one being that I cannot replicate it on JDK 9 and reason two this link provided by @Zircon derives about the issue and it being fixed as of JDK 9.

Seems like there have been several posts about this issue, another link being:

https://bugs.openjdk.java.net/browse/JDK-8040892

which itself is a duplicate of few other posts.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

Yes it's a bug but there is another way of converting this into a map which is by using identity function:

List<String> strings = Arrays.asList("3","55","3");
Map<String, List<String>> map = strings.stream()
                .collect(Collectors.toMap(Function.identity(), Arrays::asList));

By doing this you will get correct error which is

java.lang.IllegalStateException: Duplicate key [3]

For array with unique values

List<String> strings = Arrays.asList("3","55","4");

result would be

{55=[55], 3=[3], 4=[4]}
Eshu
  • 499
  • 4
  • 15
  • 1
    That will correctly report duplicate keys, but not produce the intended result when there is no conflict. – Holger Mar 29 '18 at 16:44
  • @Holger Agreed after posting the answer I noticed that btw thanks for pointing it out. – Eshu Mar 30 '18 at 14:55