Java 将两个Map对象合并为一个Map对象

实现方式是通过 putAll() 方法将多个 map 对象中的数据放到另外一个全新的 map 对象中,代码如下所示,展示了两个 map 对象的合并,如果是多个 map 合并也是用这种方式。

    public static void main(String[] args) {
        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("one", "一");
        map1.put("two", "二");
        map1.put("three", "三");

        Map<String, String> map2 = new HashMap<String, String>();
        map1.put("ten", "十");
        map1.put("nine", "九");
        map1.put("eight", "八");

        // 合并
        Map<String, String> combineResultMap = new HashMap<String, String>();
        combineResultMap.putAll(map1);
        combineResultMap.putAll(map2);

        // 合并后打印出所有内容
        for (Map.Entry<String, String> entry : combineResultMap.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }

合并后的 map 对象打印结果如下:

推荐一下本人近期维护的开源项目

Spring Boot 开源电商项目(含商城端和后台管理系统)https://github.com/newbee-ltd/newbee-mall

Spring Boot + Vue 前后端分离商城项目https://github.com/newbee-ltd/newbee-mall-vue-app

除注明转载/出处外,皆为作者原创,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。

posted @ 2018-12-25 17:48  程序员十三  阅读(90018)  评论(4编辑  收藏  举报