-3

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???

Lino
  • 19,604
  • 6
  • 47
  • 65
ohad edelstain
  • 1,425
  • 2
  • 14
  • 22

1 Answers1

3

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

ohad edelstain
  • 1,425
  • 2
  • 14
  • 22
  • This could actually be a tiny bug caused by confusing `(u, v)` to be `(k, v)` which is usually used for key/value. It certainly has nothing to do with key, as there's only access to old and new **value**. – Kayaman May 23 '18 at 12:02
  • @Kayaman you can still get the key, but you have to do it differently, not via `toMap` https://stackoverflow.com/questions/44407112/how-to-get-the-key-in-collectors-tomap-merge-function – Eugene May 23 '18 at 12:37
  • @Eugene sure, but from inside `Collectors.throwingMerger()` you don't have much chance. Looks like they removed the whole method in JDK 9 and fixed the exception to show the key as well as both values. – Kayaman May 23 '18 at 12:45
  • @Kayaman that is correct, java-9 changed that entirely – Eugene May 23 '18 at 12:48