If you have two or more Map collections in Java and you want to add them, make use of there putAll method.
Example:package org.code2care.java.collection.examples;
import java.util.HashMap;
import java.util.Map;
/**
* Example: Add two Maps
*
* Author: Code2care.org
* Date: 3nd May 2023
* Version: v1.0
*
*/
public class CombineMapsJava {
public static void main(String[] args) {
Map<String, Integer> countriesMap1 = new HashMap<>();
countriesMap1.put("China", 1);
countriesMap1.put("Japan", 2);
Map<String, Integer> countriesMap2 = new HashMap<>();
countriesMap2.put("Canada", 3);
countriesMap2.put("USA", 4);
Map<String, Integer> countriesMap = new HashMap<>();
countriesMap.putAll(countriesMap1);
countriesMap.putAll(countriesMap2);
System.out.println(countriesMap);
}
}
Output:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!