Alex Chaikoysky Alex Chaikoysky - 11 days ago 4
Java Question

Collectors.toMap with same keys(print same key)

I have this code to get map:

List<MyObject> myList = myMethod.getList();
myList.stream().collect(
Collectors.toMap(
MyObject::getKey,
MyObject::getValue,
(e1, e2) -> {
System.out.println("Duplicate keys !!!");
return e1;
},
LinkedHashMap::new
)
);


how i can print message "Duplicate keys" with duplicate key?

Answer

how i can print message "Duplicate keys" with duplicate key?

With your current code, you will get the message "Duplicate keys" with a list of MyObject which contains at least 2 instances of MyObject that have equal objects as value for getKey(), for example Arrays.asList(new MyObject("foo", "bar"), new MyObject("foo", "bar2")).

How to get the corresponding key?

Up to now it is not possible to get the corresponding key, what you currently get from the merge function are actually 2 values mapped with the same key that need to be merged to keep only one value for the corresponding key.

Your problem is a known issue that is fixed in Java 9 see JDK-8040892 for more details, the corresponding fix will allow us to get from the merge function both the key and the values to merge.

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

Comments