In this tutorial we are gonna learn how to copy one HashMap elements to another HashMap. We will be using putAll() method of HashMap class to perform this operation. Complete code as follows:
import java.util.HashMap; class HashMapDemo{ public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> hmap = new HashMap<Integer, String>(); //add elements to HashMap hmap.put(1, "AA"); hmap.put(2, "BB"); hmap.put(3, "CC"); hmap.put(4, "DD"); // Create another HashMap HashMap<Integer, String> hmap2 = new HashMap<Integer, String>(); // Adding elements to the recently created HashMap hmap2.put(11, "Hello"); hmap2.put(22, "Hi"); // Copying one HashMap "hmap" to another HashMap "hmap2" hmap2.putAll(hmap); // Displaying HashMap "hmap2" content System.out.println("HashMap 2 contains: "+ hmap2); } }
Output:
HashMap 2 contains: {1=AA, 2=BB, 3=CC, 4=DD, 22=Hi, 11=Hello}
All the elements of HashMap 1 got copied to the HashMap 2. putAll() operation does not replace the existing elements of Map rather it appends the elements to them.
Tanu says
The following lines should be:
/ Adding elements to the recently created HashMap
hmap2.put(11, “Hello”);
hmap2.put(22, “Hi”);
instead of the following:
// Adding elements to the recently created HashMap
hmap.put(11, “Hello”);
hmap.put(22, “Hi”);
I know this is a very small thing, but as your post says it is for beginner’s I guess everything should be correct.
Chaitanya Singh says
Thanks for pointing that out. It was a typo, I have fixed it.