Slightly deceiving error message on Collectors.toMap

Peter Levart peter.levart at gmail.com
Thu Apr 17 18:51:33 UTC 2014


On 04/17/2014 06:41 PM, Brian Goetz wrote:
> Rewinding:
>
> *Obviously*, it would be best if the colliding *key* were printed.
>
> Michael already observed that, at the point where the error is 
> detected, the key is not easily available.
>
> So the best fallback is to say "some key which I can't tell you mapped 
> to values V1 and V2", providing the user all the information we have 
> in the hopes of helping the user.

Or, more generaly: "two elements of resulting stream, which I can't tell 
you, mapped to the same key, which I can't tell you either, but they 
also mapped to values V1 and V2", ...

Original elements are lost by the time two maps get merged together, but 
the duplicate key could be retrieved with a little trickery:

http://cr.openjdk.java.net/~plevart/jdk9-dev/Collectors.duplicateKey/webrev.01/

Regards, Peter

>
> On 4/17/2014 12:37 PM, Michael Nascimento wrote:
>> On Thu, Apr 17, 2014 at 1:04 PM, Peter Levart 
>> <peter.levart at gmail.com> wrote:
>>> But the two values are the same (if the key->value mapper function 
>>> *is* a
>>> function), aren't they?
>>
>> No, for example:
>>
>> Stream.of(1, 1).collect(toMap(identity(), i -> Math.random()));
>>
>> Another example would be something like:
>>
>> cities.stream().collect(toMap(City::getName, identity()));
>>
>> If there are cities from different states in the collection, their
>> names might collide. Printing both values (with a decent toString)
>> will help developers to figure out their mistake.
>>
>> Regards,
>> Michael
>>



More information about the lambda-dev mailing list