Adding one HashMap to another HashMap using putAll method

In this article, we will add one HashMap contents to another HashMap using putAll() method of Map interface

 

Adding one HashSet to another HashSet :

Method signature:

void putAll(Map<? extends K, ? extends V> m);
  • This method is used to add one HashMap contents to another HashMap contents

AddOneHashMapToAnotherHashMap.java

package in.bench.resources.java.map;

import java.util.HashMap;

public class AddOneHashMapToAnotherHashMap {

	public static void main(String[] args) {

		// creating HashMap object of type <String, String>
		HashMap<String, String> hashMap1 = new HashMap<String, String>(); 

		// adding key-value pairs to 1st HashMap object
		hashMap1.put("Google", "Sundar Pichai");
		hashMap1.put("Apple", "Steve Jobs");
		hashMap1.put("Amazon", "Jeff Bezos");

		// Original HashMap-1 contents
		System.out.println("Original HashMap-1 contents: \n"
				+ hashMap1);


		// creating HashMap object of type <String, String>
		HashMap<String, String> hashMap2 = new HashMap<String, String>(); 

		// adding key-value pairs to 2nd HashMap object
		hashMap2.put("Microsoft", "Bill Gates");
		hashMap2.put("Whatsup", "Brian Acton");

		// HashMap-2 contents
		System.out.println("\n\nHashMap-2 contents: \n"
				+ hashMap2);


		// put all hashMap2 contents into original hashMap1
		hashMap1.putAll(hashMap2);

		// Modified HashMap-1 contents
		System.out.println("\n\nModified HashMap-1 contents: \n"
				+ hashMap1);
	}
}

Output:

Original HashMap-1 contents: 
{Google=Sundar Pichai, Apple=Steve Jobs, Amazon=Jeff Bezos}


HashMap-2 contents: 
{Microsoft=Bill Gates, Whatsup=Brian Acton}


Modified HashMap-1 contents: 
{Google=Sundar Pichai, Microsoft=Bill Gates, Apple=Steve Jobs, 
Amazon=Jeff Bezos, Whatsup=Brian Acton}

 

References:

 

Happy Coding !!
Happy Learning !!

How to iterate through LinkedHashMap in reverse order
How to check whether a particular value is present in HashMap