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; } } }
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.
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 .
A Set is a Collection that cannot contain duplicate elements.
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.
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.
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