handle duplicate key in Collectors.toMap() function
@Aomine: solution looks good and works for me too. Just wanted to confirm that with this it iterates twice right ?? Cause with simple solution like below it iterates only once but achieve what is required.
Map<String, String> myMap = new HashMap<>();
persons.forEach(item -> {
if(myMap.containsKey(item.getName()))
{/*do something*/}
else
myMap.put(item.getName(), item.getAddress());
});
I believe the forEach
approach along with Map.merge
would be much simpler and appropriate for the current use case :
Map<String, String> myMap = new HashMap<>();
persons.forEach(person -> myMap.merge(person.getName(), person.getAddress(), (adrs1, adrs2) -> {
System.out.println("duplicate " + person.getName() + " is found!");
return adrs1;
}));
Note: Map.merge
also uses BiFunction
(parent of BinaryOperator
as used in toMap
), hence you could correlate the merge function here to your existing desired functionality easily.