Java Program to copy all the key-value pairs from one Map into another


To copy, use the putAll() method.

Let us first create two Map −

First Map −

HashMap hm = new HashMap();
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));

Second Map −

HashMap hm2 = new HashMap();
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));

Now, copy the key-value pairs from one Map to another −

hm.putAll(hm2);

The following is an example to copy all the key-value pairs from one Map into another −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create hash map 1
      HashMap hm = new HashMap();
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      System.out.println("Map1 = "+hm);
      // Create hash map 2
      HashMap hm2 = new HashMap();
      hm.put("Bag", new Integer(1100));
      hm.put("Sunglasses", new Integer(2000));
      hm.put("Frames", new Integer(800)); 
      hm.putAll(hm2);
      System.out.println("Map1 after copying values of Map2 = "+hm);
   }
}

Output

Map1 = {Belt=600, Wallet=700}
Map1 after copying values of Map2 = {Frames=800, Belt=600, Wallet=700, Bag=1100, Sunglasses=2000}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements