Query on merge() function in HashMap: Java 8 Improvements

map1.forEach((key,value) → map2.merge(key, value, (v1, v2) → v1 + v2));

I could see that key, value are passed by forEach function. But how are v1, v2 are being passed?

Hi @Rajat_Chikkodikar, hope you are fine.

In merge function, the first two arguments are like key-value pairs, the third argument is a bit confusing as it more looks like a lambda function. We usually call it a remapping function. Let me tell you how that works. So, if the key doesn’t exist in the map then the remapping function will do nothing, but if it already exists in the map then we can make use of this remapping function.

Here, v1 represents the old value for the key and v2 represents the new value for the key, so we want this function to perform a certain operation based on old and new values of the key rather than just updating it with a new value.

So having this function passed as an argument will ensure that every time an update operation is performed, just add both old and new values. For example,

A map contains a key “A” that has a value 100, suppose it is already present in the hash map, when I will update the same key “A” with a new value that is 200, the updated value for the key “A” will be 300 not 200.

Hope that clarifies the confusion.