![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to copy all the key-value pairs from one Map into another
To copy, use the putAll() method.
Let us first create two 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);
The following is an example to copy all the key-value pairs from one Map into another −
Example
import java.util.*; public class Demo { public static void main(String args[]) { // Create hash map 1 HashMap hm = new HashMap(); hm.put("Wallet", new Integer(700)); hm.put("Belt", new Integer(600)); System.out.println("Map1 = "+hm); // Create hash map 2 HashMap hm2 = new HashMap(); hm.put("Bag", new Integer(1100)); hm.put("Sunglasses", new Integer(2000)); hm.put("Frames", new Integer(800)); 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}
Advertisements