将多个Map合并

3 篇文章 0 订阅

1.先来一个demo

public static void main(String[] args) {
    Map<String, String> map1 = new HashMap<String, String>(){{
        put("1", "a");
        put("2", "b");
        put("3", "c");
    }};
    Map<String, String> map2 = new HashMap<String, String>(){{
        put("test1", "张三");
        put("test2", "李四");
        put("test3", "王五");
    }};
    Map<String, String> resultMap = new HashMap<String, String>(){{
        putAll(map1);
        putAll(map2);
    }};
    System.out.println(resultMap);
}

2.下面将以上操作改写成工具方法

import java.util.Map;

public class MapUtil {

    /**
     * 合并多个map
     * @param maps
     * @param <K>
     * @param <V>
     * @return
     * @throws Exception
     */
    public static <K, V> Map mergeMaps(Map<K, V>... maps) {
        Class clazz = maps[0].getClass(); // 获取传入map的类型
        Map<K, V> map = null;
        try {
            map = (Map) clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (int i = 0, len = maps.length; i < len; i++) {
            map.putAll(maps[i]);
        }
        return map;
    }
}

3.调用

将demo中得到resultMap的那行换成下面的即可

Map<String, String> resultMap = MapUtil.mergeMaps(new Map[]{map1, map2});

 

 

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值