Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Collectors.toMap report value instead of key on Duplicate Key error?

Tags:

This is really a question about a minor detail, but I'm under the impression to get something wrong here. If you add duplicate keys using Collectors.toMap-method it throws an Exception with message "duplicate key ". Why is the value reported and not the key? Or even both? This is really misleading, isn't it?

Here's a little test to demonstrate the behaviour:

import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors;  public class TestToMap {      public static void main(String[] args) {          List<Something> list = Arrays.asList(             new Something("key1", "value1"),             new Something("key2", "value2"),             new Something("key3", "value3a"),             new Something("key3", "value3b"));          Map<String, String> map = list.stream().collect(Collectors.toMap(o -> o.key, o -> o.value));         System.out.println(map);     }      private static class Something {         final String key, value;          Something(final String key, final String value){             this.key = key;             this.value = value;         }     } } 
like image 550
Tim Büthe Avatar asked Oct 14 '16 09:10

Tim Büthe


People also ask

What does duplicate key error mean?

A duplicate key error means that you have tried to insert a row with the same key value as some other row already indexed by the named index.

What does duplicate key value mean?

Duplicate key values occur when the value of an indexed column is identical for multiple rows. For example, suppose that the third and fourth leaf nodes of a B-tree structure contain the key value Smith .

Can Collection store duplicate values?

A Set is a Collection that cannot contain duplicate elements.

Which key should not store duplicate values?

Set is not allowed to store duplicated values by definition. If you need duplicated values, use a List. As specified on the documentation of the interface, when you try to add a duplicated value, the method add returns false, not an Exception.


1 Answers

This is reported as a bug, see JDK-8040892, and it is fixed in Java 9. Reading the commit fixing this, the new exception message will be

String.format("Duplicate key %s (attempted merging values %s and %s)", k, u, v) 

where k is the duplicate key and u and v are the two conflicting values mapped to the same key.

like image 196
Tunaki Avatar answered Oct 14 '22 20:10

Tunaki