What is the HashMap.merge() method in Java?
The merge method in Java will:
-
Insert a new entry if the mapping for the key is not present.
-
If a mapping for the key is already present, then the value associated with the key will be assigned based on the value returned from the
argument of theBiFunctionA functional interface that accepts two arguments and produces a result. mergemethod.
Syntax
mapObj.merge(key, value, BiFunction);
-
key: The key for which the value is to be added or merged. -
value: The value to be associated withkey. If there is already a value associated with thatkeyin the map, thenBiFunctionrecomputes the value. -
BiFunction: A functional interface that takes two arguments,oldValandnewVal, and returns a single value.
Example
import java.util.HashMap;class merge {public static void main( String args[] ) {HashMap<String, Integer> map = new HashMap<String, Integer>();map.put("Maths", 50);map.put("Science", 60);map.put("Programming", 70);System.out.println( "The map is - \n" + map);map.merge("Economics", 40, (oldVal, newVal) -> { return oldVal + newVal; });System.out.println( "\nThe map afer executing - map.merge(Economics, 40, (oldVal, newVal) -> { return oldVal + newVal; }); \n" + map);map.merge("Maths", 40, (oldVal, newVal) -> { return oldVal + newVal; });System.out.println( "\n\nThe map afer executing - map.merge(Maths, 40, (oldVal, newVal) -> { return oldVal + newVal; }); \n" + map);}}
In the code above, we have:
-
Created a
HashMapwith the namemapand added some entries into it. -
Called the
mergemethod of theHashMapobject for theEconomicskey.
map.merge("Economics", 40, (oldVal, newVal) -> { return oldVal + newVal; });
The call above to the merge method will check if the Economics key is already present on the map. In our case, the Economics key is not present in the map, so a new entry with the Economics key and value 40 will be added to the map object.
- We again called the
mergemethod of theHashMapobject for the keyMaths.
map.merge("Maths", 40, (oldVal, newVal) -> { return oldVal + newVal; });
The above call to the merge method will check if the Maths key is already present on the map. In our case, the Maths key is present in the map, so the BiFunction will be executed and the value returned from the BiFunction is updated for the Maths key. In our BiFunction, we returned the sum of the old value and the new value from the BiFunction.