Friday, October 14, 2022

Java Map merge() With Examples

In this post you'll learn about merge() method in java.util.map which is added in Java 8.

Syntax of the merge() method is as given below.

V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)

merge() method works in the following way-

  1. If specified key is not present in the map or associated with null value then add the passed key and the value (second argument) to the Map.
  2. If specified key is already present in the Map then use the remapping function (third argument) to compute a new value for this key. That’s where this method derives its name from, if key is already there you have access to both old value and new value and using them you can compute an altogether new value which can then replace the value associated with the specified key.
  3. If the remapping function returns null then the mapping is removed from the Map.

This working of the merge() method can be explained as

V oldValue = map.get(key);
 V newValue = (oldValue == null) ? value : remappingFunction.apply(oldValue, value);
 if (newValue == null)
     map.remove(key);
 else
     map.put(key, newValue);

merge() method Java Example

1. In this example there is a HashMap having some items and their prices as key, value pairs. Using merge() we'll pass a key that is not present in the Map.

import java.util.HashMap;
import java.util.Map;

public class MergeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    
    itemMap.merge("Belt", 750, (oldValue, newValue) -> newValue);
    System.out.println("*** Map After merge ***");
    System.out.println(itemMap);
  }
}

Output

{Shirt=800, Shoes=2000, Trousers=1200}
*** Map After merge ***
{Belt=750, Shirt=800, Shoes=2000, Trousers=1200}

Since key was not already present in the Map so 750 (second argument) is taken as value. Remapping function is not considered in this case.

2.In this example we'll use the same item map and specify a key that is already present in the Map. In the merge method there is a remapping function that increases the price by 20%. You can notice that the value computed using remapping function replaces the value associated with the key.

public class MergeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", 750);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    
    itemMap.merge("Belt", 750, 
      (oldValue, newValue) -> oldValue + (oldValue *20/100));
    System.out.println("*** Map After merge ***");
    System.out.println(itemMap);
  }
}

Output

{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}
*** Map After merge ***
{Shirt=800, Belt=900, Shoes=2000, Trousers=1200}

3. In this example we'll take the scenario where remappingFunction of the merge() method returns null. In that case the (key, value) pair should be removed from the Map.

public class MergeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", 750);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    
    itemMap.merge("Belt", 750, 
      (oldValue, newValue) -> null);
    System.out.println("*** Map After merge ***");
    System.out.println(itemMap);
  }
}

Output

{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}
*** Map After merge ***
{Shirt=800, Shoes=2000, Trousers=1200}

As you can see Map entry with key as "Belt" is removed from the Map as the remapping function returned null.

4. If you want to recompute all the values in the Map, merge() method is very convenient. Suppose in our item map we want to increase prices for all the items by 20%.

public class MergeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", 750);
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    
    itemMap.forEach((k,v) -> itemMap.merge(k, v, 
          (oldValue, newValue)-> oldValue+ (oldValue * 20/100)));
    System.out.println("*** Map After merge ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}
*** Map After merge ***
{Shirt=960, Belt=900, Shoes=2400, Trousers=1440}

5. You can merge two HashMaps using merge() method too.

public class MergeDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap1 = new HashMap<>();
    itemMap1.put("Trousers", 1200);
    itemMap1.put("Shirt", 800);
    itemMap1.put("Shoes", 2000);
    System.out.println("*** First Map ***");
    System.out.println(itemMap1);
    Map<String, Integer> itemMap2 = new HashMap<>();
    itemMap2.put("Shirt", 900);
    itemMap2.put("Belt", 750);
    System.out.println("*** Second Map ***");
    System.out.println(itemMap2);
    
    //Merging two Maps
    itemMap1.forEach((k,v) -> itemMap2.merge(k, v, 
          (oldValue, newValue)-> oldValue > newValue? oldValue : newValue));
    System.out.println("*** Map After merge ***");
    System.out.println(itemMap2);
  }
}

Output

*** First Map ***
{Shirt=800, Shoes=2000, Trousers=1200}
*** Second Map ***
{Shirt=900, Belt=750}
*** Map After merge ***
{Shirt=900, Belt=750, Shoes=2000, Trousers=1200}

Here merge method is used with Map itemMap2 so that will have the merged values. One of the key "Shirt" is present in both of the Maps so remapping function is used to compute the value (here logic is to take the highest value).

That's all for this topic Java Map merge() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map getOrDefault() Method With Examples
  2. Java Map computeIfAbsent() With Examples
  3. equals() And hashCode() Methods in Java
  4. Difference Between HashMap And ConcurrentHashMap in Java
  5. How to Sort a HashMap in Java

You may also like-

  1. Java is a Strongly Typed Language
  2. static Block in Java
  3. Serialization and Deserialization in Java
  4. Java Program to Convert a File to Byte Array
  5. How to Use ngFor and ngIf on Same Element in Angular
  6. Spring util-namespace Example For Wiring Collection
  7. Spring Batch Processing With List of Objects in batchUpdate() Method
  8. Ternary Operator in Python

No comments:

Post a Comment