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 BiFunction
merge
method.
mapObj.merge(key, value, BiFunction);
key
: The key for which the value is to be added or merged.
value
: The value to be associated with key
. If there is already a value associated with that key
in the map, then BiFunction
recomputes the value.
BiFunction
: A functional interface that takes two arguments, oldVal
and newVal
, and returns a single value.
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 HashMap
with the name map
and added some entries into it.
Called the merge
method of the HashMap
object for the Economics
key.
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.
merge
method of the HashMap
object for the key Maths
.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
.