Java HashMap.merge() method explanation with examples

Java HashMap.merge() method explanation with examples:

Java HashMap.merge() method is used to merge an item to an existing HashMap. In this post, we will learn how to use this method with examples in Java.

Definition of HashMap.merge():

HashMap.merge() is defined as like below:

hashmap.merge(key, value, remappingFunction)


  • key is the key of the pair to insert. We can also pass any existing key.
  • value is the value for the key to merge.
  • remappingFunction is a function that is used to find the result if key is associated with a value. If it returns null, then the mapping for that key is removed.

Return value of HashMap.merge():

HashMap.merge method returns the new value for the provided key. It returns null, if no value is there for the key.

Example of HashMap.merge() with a key that doesn’t exist:

Let’s take a look at different examples of HashMap.merge() to see how it works.


import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, String> productMap = new HashMap<>();

        productMap.put("Product-1", "10");
        productMap.put("Product-2", "20");
        productMap.put("Product-3", "30");

        System.out.println("Given HashMap "+productMap);

        String result = productMap.merge("Product-4", "40", (oldPrice, newPrice) -> oldPrice + "=>" + newPrice);
        System.out.println("Result value: " + result);

        System.out.println("New HashMap: " + productMap);

In this program, we have created one HashMap productMap and added three key-value pairs.

You might also like: