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

Java 8Object Oriented ProgrammingProgramming

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}
raja
Published on 16-Jan-2019 07:03:44
Advertisements