Java HashMap merge()

If the specified key is already associated with a value, the method replaces the old value with the result of the specified function.

The syntax of the merge() method is:

hashmap.merge(key, value, remappingFunction)

Here, hashmap is an object of the HashMap class.


merge() Parameters

The merge() method takes 3 parameters:

  • key - key with which the specified value is to be associated
  • value - value to be associated with key, if key is already associated with any value
  • remappingFunction - result to be associated with key if key is already associated with a value

merge() Return Value

  • returns the new value associated with the key
  • returns null if no value associated with key

Note: If remappingFunction results null, then the mapping for the specified key is removed.


Example 1: HashMap merge() to Insert New Entry

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create an HashMap
    HashMap<String, Integer> prices = new HashMap<>();

    // insert entries to the HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: " + prices);

    int returnedValue = prices.merge("Shirt", 100, (oldValue, newValue) -> oldValue + newValue);
    System.out.println("Price of Shirt: " + returnedValue);

    // print updated HashMap
    System.out.println("Updated HashMap: " + prices);
  }
}

Output

HashMap: {Pant=150, Bag=300, Shoes=200}
Price of Shirt: 100
Updated HashMap: {Pant=150, Shirt=100, Bag=300, Shoes=200}

In the above example, we have created a hashmap named prices. Notice the expression,

prices.merge("Shirt", 100, (oldValue, newValue) -> oldValue + newValue)

Here, we have used the lambda expression, (oldValue, newValue) -> oldValue + newValue) as the remapping function. To learn more about lambda expression, visit Java Lambda Expressions.

Since the key Shirt is not present in prices, the merge() method inserts the mapping Shirt=100. And, the result from remapping function is ignored.


Example 2: HashMap merge() to Insert Entry with Duplicate Key

import java.util.HashMap;

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

    // insert entries to the HashMap
    countries.put("Washington", "America");
    countries.put("Canberra", "Australia");
    countries.put("Madrid", "Spain");
    System.out.println("HashMap: " + countries);

    // merge mapping for key Washington
    String returnedValue = countries.merge("Washington", "USA", (oldValue, newValue) -> oldValue + "/" + newValue);
    System.out.println("Washington: " + returnedValue);

    // print updated HashMap
    System.out.println("Updated HashMap: " + countries);
  }
}

Output

HashMap: {Madrid=Spain, Canberra=Australia, Washington=America}
Washington: America/USA
Updated HashMap: {Madrid=Spain, Canberra=Australia, Washington=America/USA}, 

In the above example, we have created a hashmap named countries. Notice the expression,

countries.merge("Washington", "USA", (oldValue, newValue) -> oldValue + "/" + newValue)

Here, we have used the lambda expression, (oldValue, newValue) -> oldValue + "/" + newValue) as the remapping function.

Since key Washington is already present in countries, the old value is replaced by the value returned by remapping function. Hence, the mapping for Washington includes value America/USA.


Example 3: HashMap merge() to Merge two HashMaps

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create an HashMap
    HashMap<String, Integer> prices1 = new HashMap<>();

    // insert entries to the HashMap
    prices1.put("Pant", 230);
    prices1.put("Shoes", 350);
    System.out.println("HashMap 1: " + prices1);

    // create another hashmap
    HashMap<String, Integer> prices2 = new HashMap<>();

    //insert entries to the HashMap
    prices2.put("Shirt", 150);
    prices2.put("Shoes", 320);
    System.out.println("HashMap 2: " + prices2);

    // forEach() access each entries of prices2
    // merge() inserts each entry from prices2 to prices1
    prices2.forEach((key, value) -> prices1.merge(key, value, (oldValue, newValue) -> {
      
      // return the smaller value
      if (oldValue < newValue) {
        return oldValue;
      }
      else {
        return newValue;
      }
    }));

    System.out.println("Merged HashMap: " + prices1);
  }
}

Output

HashMap 1: {Pant=230, Shoes=350}
HashMap 2: {Shirt=150, Shoes=320}
Merged HashMap: {Pant=230, Shirt=150, Shoes=320}

In the above example, we have created two hashmaps named prices1 and prices2. Notice the code,

    prices2.forEach((key, value) -> prices1.merge(key, value, (oldValue, newValue) -> {
      if (oldValue < newValue) {
        return oldValue;
      }
      else {
        return newValue;
      }
    }));

Here, the HashMap forEach() method accesses each entry of the hashmap prices2 and merges it to the hashmap prices1. We have used two lambda expressions:

  • (key, value) -> prices.merge(...) - It accesses each entry of prices1 and passes it to the merge() method.
  • (oldValue, newValue) -> {...} - It is a remapping function. It compares two values and returns the smaller value.

Since the key Shoes is present in both the hashmap, the value of Shoes is replaced by the result of the remapping function.


Java HashMap merge() Vs. putAll

We can also use the putAll() method to merge two hashmaps. However, if a key is present in both hashmaps, the old value is replaced by the new value.

Unlike the merge(), the putAll() method does not provide the remapping function. Hence, we cannot decide what value to store for duplicate keys.

To learn more about the putAll() method, visit Java HashMap putAll().

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges