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



In Java, maps are a powerful and versatile way to store key-value pairs. Often, you may find the need to merge the contents of one map into another. This can be done effortlessly using the putAll method available in the Map interface. Let's explore this functionality with an example and a step-by-step explanation.

Problem Statement

The goal is to combine two maps by adding all entries or selectively adding entries without overwriting existing ones in the destination map.

Input

Map 1 (Destination Map)

Wallet: 700

Belt: 600

Map 2 (Source Map) 

Bag: 1100  

Sunglasses: 2000
Frames: 800

Output 

Map1 = {Wallet=700, Belt=600}  

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

Using putAll

The putAll method of the Map interface allows you to copy all the key-value pairs from one map into another. If a key in the source map already exists in the destination map, its value will be updated with the value from the source 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);

Example

Below is an example of copying all the key-value pairs from one Map into another ?

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create hash map 1
      HashMap<String, Integer> hm = new HashMap<>();
      hm.put("Wallet", 700);  // Using autoboxing
      hm.put("Belt", 600);    // Using autoboxing
      System.out.println("Map1 = " + hm);

      // Create hash map 2
      HashMap<String, Integer> hm2 = new HashMap<>();
      hm2.put("Bag", 1100);          // Using autoboxing
      hm2.put("Sunglasses", 2000);  // Using autoboxing
      hm2.put("Frames", 800);       // Using autoboxing

      // Copy all entries from hm2 to hm
      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}

Time Complexity: O(n), where n is the number of entries in the source map.
Space Complexity: O(1), as no additional space is used beyond the original map.

Conclusion

The putAll method provides a quick and efficient way to merge two maps in Java. It overwrites existing keys in the destination map with values from the source map. For use cases requiring all entries to be added without condition, putAll is the simplest solution.

Updated on: 2024-12-26T20:45:48+05:30

590 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements