Java: How to Add two Maps with example


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:

{Canada=3, USA=4, China=1, Japan=2}

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap