问题
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
来源:https://stackoverflow.com/questions/50487731/java8-tomap-exception-message-confusing