An instance of the Java HashMap calls the merge()
function, which inserts a new key-value pair in the HashMap.
To use the merge()
function with HashMap, the program needs to import the java.util.HashMap
module:
import java.util.HashMap;
map
, an instance of the Java Hashmap, can call the merge()
function as illustrated below:
The merge()
function accepts the following three parameters:
key
: The key for the new key-value pair that is inserted.value
: The value for the new key-value pair that is inserted.remappingFunction
: The function for mapping the value if an existing value is already associated with the key.The merge()
function returns the value associated with the key. merge()
returns null
if no value is associated with the key.
If the remappingFunction
results in a null value, the key-value pair is removed from the HashMap.
The following example demonstrates how to use the merge()
function with a Java HashMap.
results
and indicates in line 7 that the first element of a pair is a string and the second element is an integer.results
HashMap through the put()
method and displays the HashMap.remappingFunction
is a Java lambda expression; it adds the old value and the new value and associates it to the key Sara
if Sara
is already a key in the HashMap. Since the key Sara
is not present in the HashMap, the associated value is 90
.Sara
is already present in the HashMap. Therefore, the remappingFunction
adds the old marks, which are 95, and new marks, which are 76, and associates the result with the key. Hence, the new value associated with Sara
is 166.import java.util.HashMap;class ExampleHashMap {public static void main(String[] args) {// create a new hashmapHashMap<String, Integer> results = new HashMap<>();System.out.println("A HashMap for mapping marks to students");// add elements to the hashmapresults.put("Ali", 89);results.put("Ahmed", 95);results.put("Sana", 70);results.put("Amna", 100);//display the hashmapSystem.out.println("Updated HashMap: " + results);// Example 1int val = results.merge("Sara", 90, (val1, val2) -> val1+val2);System.out.println("The new value is " + val);//display the hashmapSystem.out.println("Updated HashMap: " + results);// Example 2val = results.merge("Sara", 76, (val1, val2) -> val1+val2);System.out.println("The new value is" + val);//display the hashmapSystem.out.println("Updated HashMap: " + results);}}
Free Resources