-1

The code is as below. I am seeing Duplicate key , illegal state Exception.

List<User> allusers = Helper.getAllUsers(someKey);
Map<String, User> allusersMap = allusers.stream()
.collect(Collectors.toMap(originalUser-> originalUser.getName(),
originalUser-> originalUser));
Eternal_Explorer
  • 1,119
  • 3
  • 14
  • 26
  • 2
    `toMap()` takes 3 argument, and the third one is `BinaryOperator `which can help you in ignoring duplicates. `(a,b)->a` would solve your problem. – Vishwa Ratna Jan 13 '20 at 05:33

1 Answers1

3

The Java docs on toMap explain this pretty clearly:

If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys may have duplicates, use toMap(Function, Function, BinaryOperator) instead.

So your data have multiple users with the same name, and toMap is working as intended. It's always good to rtm :-)

Gene
  • 46,253
  • 4
  • 58
  • 96
  • Resolved using the BinaryOperator List allusers = Helper.getAllUsers(someKey); Map allusersMap = allusers.stream() .collect(Collectors.toMap(originalUser-> originalUser.getName(), originalUser-> originalUser,(userObj1, userObj2) -> userObj1)); – Eternal_Explorer Jan 13 '20 at 09:06