Write a Java program to copy all of the mappings from the specified map to another map


This is a Java program that demonstrates how to copy all elements from one HashMap to another. Here's how it works:

  • First, two HashMap objects are created using the HashMap class. These HashMaps will be used to store integer keys and string values.
  • Key-value pairs are added to the first HashMap, hash_map1, using the put() method.
  • Key-value pairs are added to the second HashMap, hash_map2, using the put() method.
  • The putAll() method is used to copy all elements from hash_map1 to hash_map2.
  • The contents of hash_map2 are printed to the console using the println() method.

Source Code

import java.util.*;  
public class CopyAll
{  
	public static void main(String args[])
	{
		HashMap <Integer,String> hash_map1 = new HashMap <Integer,String> ();
		HashMap <Integer,String> hash_map2 = new HashMap <Integer,String> ();
		hash_map1.put(1, "Cpp");
		hash_map1.put(2, "Python");
		hash_map1.put(3, "Java");
		System.out.println("HashMap 1 : " + hash_map1);
		hash_map2.put(4, "MySql");
		hash_map2.put(5, "C");
		hash_map2.put(6, "Php");
		hash_map2.put(7, "Ruby");
		System.out.println("HashMap 2 : " + hash_map2);
 
		hash_map2.putAll(hash_map1);
		System.out.println("\nNow values in HashMap 2 : " + hash_map2);
	}
}

Output

HashMap 1 : {1=Cpp, 2=Python, 3=Java}
HashMap 2 : {4=MySql, 5=C, 6=Php, 7=Ruby}

Now values in HashMap 2 : {1=Cpp, 2=Python, 3=Java, 4=MySql, 5=C, 6=Php, 7=Ruby}