Last Updated : 12 Jul, 2025
In Java, the merge() method of the HashMap class is used to either add new key-value pairs or update the existing one in the map by merging values using a specified function.
Note: It either adds the new entry or updates an existing one by merging values together
Example 1: The below Java program demonstrates the use of merge() method to add new key-value pairs and update the existing ones by combining old and new values using the Lambda function.
Java
// Java program to demonstrate adding and updating
// key-value pairs using merge()
import java.util.HashMap;
public class Main {
public static void main(String[] args)
{
// creating a HashMap to store key-value pairs
HashMap<String, Integer> hm = new HashMap<>();
hm.put("A", 10);
hm.put("B", 20);
// use merge() for a key that
// is not present in the map
hm.merge("C", 30,
(oldValue, newValue) -> oldValue + newValue);
// use merge() for a key that
// is already present in the map
hm.merge("A", 15,
(oldValue, newValue) -> oldValue + newValue);
System.out.println(hm);
}
}
{A=25, B=20, C=30}Syntax of HashMap merge() Method
default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)
Parameters: This method takes three parameters.
Return Type: Return the new value associated with the key or null if the new value is null.
Example 2: The below Java program demonstrates the use of merge() to update the existing value or insert the new key-value pair using a custom BiFunction.
Java
// Java program to demonstrate merging
// string values using merge()
import java.util.HashMap;
public class Geeks {
public static void main(String[] args)
{
HashMap<String, String> hm = new HashMap<>();
hm.put("A", "Hello");
hm.put("B", "World");
// use merge() for a key that
// is already present in the map
hm.merge("A", "Java",
(oldValue,newValue) -> oldValue + " " + newValue);
// use merge() for the key that
// is not present in the map
hm.merge("C", "Programming",
(oldValue, newValue) -> oldValue + newValue);
System.out.println(hm);
}
}
{A=Hello Java, B=World, C=Programming}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4