cmfu
cmfu

Reputation: 19

Why Collectors.toMap (in JDK8 java.util.stream )not allowed the same key?

If we put two k-v pairs into a hashmap with the same key, the second value will override the first one. but if we do this by Collectors.toMap, it will throw en exception with the message: "Duplicate key".

I know how to fix it, but I want to know why the Collectors design like this.

Upvotes: 1

Views: 442

Answers (2)

Andreas
Andreas

Reputation: 159185

With map.put(key, value), you haven't lost any information, even if the new entry replaces an existing entry. That is because the method returns the old value, so you only lose information if you don't use the return value, and the method cannot detect if you do, and they cannot force you.

With Collectors.toMap(keyMapper, valueMapper), information will be lost if there is a duplicate key. For safety, it will reject duplicate keys, by throwing an exception. You can accept duplicate keys by providing a mergeFunction as a third parameter to explicitly ignore the old value, e.g. using lambda expression (a,b) -> b to discard the old value. Here they have the ability to force you to consider the issue.

Upvotes: 3

M A
M A

Reputation: 72884

It depends on the collector method: toMap​(Function<? super T,​? extends K> keyMapper, Function<? super T,​? extends U> valueMapper, BinaryOperator<U> mergeFunction) allows you to specify a merge function to merge values for the same duplicate key.

Upvotes: 1

Related Questions