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