How to Copy One HashMap Elements to Another HashMap Example

In the last tutorial I have shared how to serialize HashMap in java. In this tutorial we are going to learn about how to copy one HashMap elements to another HashMap. We will be using putAll() method to achieve the objective.

Syntax :

public void putAll(Map m) : copies all of the mappings from the specified map to the map m.

Program to Copy One HashMap Elements to Another HashMap

All of the elements of HashMap1 got copied to HashMap2.

import java.util.*;

 public class HashMapPutAllExample {
    public static void main(String args[]) {
        
    // Creating a HashMap of Integer keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
    hashmap.put(1, "Value1");
    hashmap.put(2, "Value2");
    hashmap.put(3, "Value3");
    hashmap.put(4, "Value4");
    hashmap.put(5, "Value5");
    // Create another HashMap
     HashMap<Integer, String> hashmap2 = new HashMap<Integer, String>();
     // Adding elements to the recently created HashMap
     hashmap2.put(11, "Apple");
     hashmap2.put(22, "Banana");
 
     // Copying one HashMap "hashmap" to another HashMap "hashmap2"
     hashmap2.putAll(hashmap);
 
     // Displaying HashMap "hashmap2" content
     System.out.println("HashMap 2 contains: "+ hashmap2);
  }
}

Output


HashMap 2 contains: {1=Value1, 2=Value2, 3=Value3, 4=Value4, 5=Value5, 22=Banana, 
11=Apple}





About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry