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}