Java8 toMap exception message confusing [duplicate

2019-09-21 22:24发布

问题:

This question already has an answer here:

  • Why does Collectors.toMap report value instead of key on Duplicate Key error? 4 answers
  • Java 8 toMap IllegalStateException Duplicate Key 2 answers
  • Ignore duplicates when producing map using streams 6 answers
  • Alternative for throwingMerger in Java 8 1 answer
  • Collectors.toMap with same keys(print same key) 2 answers

Got this exception:

java.lang.IllegalStateException: Duplicate key 50  

I looked over every map that is using that code, and there is no such key It took me a while but I found the problem but it is confusing and very problematic to understand don't know why they did it like this

this is my code:

    List<Person> listOfPeople = new LinkedList<Person>();

    Map<String, Integer> myMap = listOfPeople
                .stream()
                .collect(Collectors.toMap(
                                        Person::getNameInString,
                                        Person::getAgeInInt
                                )
                );

My map is String to Integer, so were did 50 came from???

回答1:

The Answer is that:
I took me some digging finding the relevant input causing this problem.

It turns out that I had two people with the same name,
So why not print:

java.lang.IllegalStateException: Duplicate key "Ohad Edelstein"

For example.

were did they get 50?!?!
50 is the age, of the first "Ohad Edelstein"!

How did I get that? I looked in the documentation and found this method:

private static <T> BinaryOperator<T> throwingMerger() {
    return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
}

What is u and v? This is the method calling it in HashMap

remappingFunction.apply(old.value, value)

What is the point of printing the value?!?! why not write something like

java.lang.IllegalStateException: Duplicate key "Ohad Edelstein", first value 50 second value 35

Any way, hope it will prevent others from at least part of the frustration

FYI, to handle the exception issue - if you are fine with it, you can take a look at this answer:
Ignore duplicates when producing map using streams