Skip to content
Advertisement

handle duplicate key in Collectors.toMap() function

I am creating a map which its (key,value) will be (name, address) in my Person object:

JavaScript

In the duplicate key situation, I would like to skip to add the second address to the map and would like to log the name also. Skipping the duplicate address I can do already using mergeFunction, but in oder to log the name I need in this mergeFunction the person object, something like:

JavaScript

I am getting stuck by passing person object to this merge function.

Advertisement

Answer

if you want to access the whole person object in the merge function then pass Function.identity() for the valueMapper:

JavaScript

But as you can see the resulting map values are Person objects, if you still want a Map<String, String> as a result and still access the whole Person object in the mergeFunction then you can do the following:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement