Java Utility Library

Java Hashtable - merge() Method



The java.util.Hashtable.merge() method is used to merge multiple mapped values for a key. If a specified key is not already associated with a value or null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null.

If the function returns null the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.

Syntax

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

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

key Specify the key with which the resulting value is to be associated.
value Specify the non-null value to be merged with the existing value associated with the key or, if no existing value or a null value is associated with the key, to be associated with the key.
remappingFunction Specify the function to recompute a value if present.

Return Value

Returns the new value associated with the specified key, or null if no value is associated with the key.

Exception

NA.

Example:

In the example below, the java.util.Hashtable.merge() method is used to merge multiple mapped values for a key.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a Hashtable
    Hashtable<Integer, String> Htable1 = new Hashtable<Integer, String>();
    Hashtable<Integer, String> Htable2 = new Hashtable<Integer, String>();

    //populating Htable1
    Htable1.put(101, "John");
    Htable1.put(102, "Marry");
    Htable1.put(103, "Kim");

    //populating Htable2
    Htable2.put(101, "M");
    Htable2.put(102, "F");
    Htable2.put(103, "M");    

    //printing the Hashtable
    System.out.println("Htable1 contains: " + Htable1);  
    System.out.println("Htable2 contains: " + Htable2);   

    //merging two Hashtables into Htable1
    Htable2.forEach((k,v) ->
      Htable1.merge(k, v, (v1, v2) -> 
        (v1 == v2) ? 
          v1 : v1 + ", " + v2 )   
    ); 

    //printing the Hashtable
    System.out.println("Htable1 contains: " + Htable1);  
  }
}

The output of the above code will be:

Htable1 contains: {103=Kim, 102=Marry, 101=John}
Htable2 contains: {103=M, 102=F, 101=M}
Htable1 contains: {103=Kim, M, 102=Marry, F, 101=John, M}

❮ Java.util - Hashtable