Java Utility Library

Java WeakHashMap - putAll() Method



The java.util.WeakHashMap.putAll() method is used to copy all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.

Syntax

public void putAll(Map<? extends K,? extends V> m)

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


Parameters

m Specify mappings to be stored in this map.

Return Value

void type.

Exception

Throws NullPointerException, if the specified map is null.

Example:

In the example below, the java.util.WeakHashMap.putAll() method is used to copy all of the mappings from the Map2 to Map1.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating weakhashmaps
    WeakHashMap<Integer, String> Map1 = new WeakHashMap<Integer, String>();
    WeakHashMap<Integer, String> Map2 = new WeakHashMap<Integer, String>();

    //populating Map2
    Map2.put(101, "John");
    Map2.put(102, "Marry");
    Map2.put(103, "Kim");
    Map2.put(104, "Jo");

    //printing Map1
    System.out.println("Before putAll, Map1 contains: " + Map1);    

    //copy mapping from Map2 into Map1
    Map1.putAll(Map2); 

    //printing Map1
    System.out.println("After putAll, Map1 contains: " + Map1);  
  }
}

The output of the above code will be:

Before putAll, Map1 contains: {}
After putAll, Map1 contains: {104=Jo, 101=John, 103=Kim, 102=Marry}

❮ Java.util - WeakHashMap