将多个Map合并

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});

 

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页