Java HashMap putAll(Map m) Example

The put(K key, V value) method of java.util.HashMap class associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced whereas putAll(Map<? extends K,? extends V> m) method copies 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.

Signature

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

This method copies 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. Throws java.lang.NullPointerException if the specified map is null

Example

The following example shows the usage of java.util.HashMap.putAll(m) method.

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

public class PutAllMethodHashMapExample 
{
    public static void main(String args[])
    {
        // create an empty HashMap
        HashMap<Integer,String> hashMap1 = new HashMap<Integer,String>();
        HashMap<Integer,String> hashMap2 = new HashMap<Integer,String>();
        
        // use put() method to put elements to the HashMap1
        hashMap1.put(1,"Element1");
        hashMap1.put(2,"Element2");
        hashMap1.put(3,"Element3");
        hashMap1.put(4,"Element4");
        hashMap1.put(5,"Element5");
        
        System.out.println("**Elements of hashMap1 before putAll()**");
        
        //Print the elements of hashMap1
        for (Map.Entry<Integer,String> entry : hashMap1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
        
        // use put() method to put elements to the HashMap2
        hashMap2.put(10,"Element10");
        hashMap2.put(11,"Element11");
        hashMap2.put(12,"Element12");
        hashMap2.put(13,"Element13");
        hashMap2.put(14,"Element14");
        
        //Put all the elements of hashMap2 to hashMap1
        hashMap1.putAll(hashMap2);
        
        System.out.println("**Elements of hashMap1 after putAll()**");
        //Print the elements of hashMap1
        for (Map.Entry<Integer,String> entry : hashMap1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
    }
}

Output

**Elements of hashMap1 before putAll()**
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 3 Value : Element3
Key : 4 Value : Element4
Key : 5 Value : Element5
**Elements of hashMap1 after putAll()**
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 3 Value : Element3
Key : 4 Value : Element4
Key : 5 Value : Element5
Key : 10 Value : Element10
Key : 11 Value : Element11
Key : 12 Value : Element12
Key : 13 Value : Element13
Key : 14 Value : Element14

Leave a Reply

Your email address will not be published. Required fields are marked *