博客引用处(以下内容在原有博客基础上进行补充或更改,谢谢这些大牛的博客指导):
https://blog.csdn.net/u010999809/article/details/80721333
https://blog.csdn.net/pacosonswjtu/article/details/78068140
https://blog.csdn.net/u013066244/article/details/80151670
https://blog.csdn.net/sinat_29384657/article/details/52933817
https://www.cnblogs.com/shalf/p/6206935.html
- 基础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);
}
- 下面将以上操作改写成工具方法
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;
}
}
- demo中就可以改为:
Map<String, String> resultMap = MapUtil.mergeMaps(new Map[]{map1, map2});
- Ps:
当使用putAll时,如果我们改变原集合中的值,那么是并不会影响已经putAll到新集合中的数据的。
putAll 后putAll进入的Map如果和前面已经插入的数据的Key相同,那么后进入的会覆盖前进入的。