JDK1.8为Map提供了丰富的Map合并方法,包括Map中声明的putAll、merge方法,Stream API 提供的Stream.concat(),Stream.of(),以及Stream API 的增强库提供的append().toMap方法都提供了很好的解决方案。Stream的可以参考一下https://blog.csdn.net/w605283073/article/details/82987157。
本文主要以HashMap为例,看一下putAll和merge方法的使用和源码。
首先是putAll,putAll方法在jdk1.7之前就有,在1.7的代码中存在可能需要多次扩容的问题(实际上一定会多次扩容的),1.8的代码中JDK的大神们应该是做了权衡,首先会去容量较大的作为扩容后的容量,然后在实际合并过程中如果容量不够会继续扩容。
/**
* Implements Map.putAll and Map constructor
*
* @param m the map
* @param evict false when initially constructing this map, else
* true (relayed to method afterNodeInsertion).
*/
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
//1.计算容量,取待合并Map中较大的容量,为什么没有取两个Map的容量和,应该是考虑的map存在重复键可能导致的空间浪费
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
//2.实际插入的过程中也会检查容量,必要的时候进行扩容
putVal(hash(key), key, value, false, evict);
}
}
}
使用方法,首先定义一个空的HashMap然后依次putAll就可以了。
Map<String, String> map1 = new HashMap<String, String>();
map1.put("Jan", "一月");
map1.put("Feb", "二月");
map1.put("Mar", "三月");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("Apr", "四月");
map2.put("May", "五月");
map2.put("June", "六月");
map2.put("July", "七月");
// 合并
Map<String, String> combineResultMap = new HashMap<String, String>();
System.out.println("combineResultMap集合容量0:"+combineResultMap.size());
combineResultMap.putAll(map1);
System.out.println("combineResultMap集合容量1:"+combineResultMap.size());
combineResultMap.putAll(map2);
System.out.println("combineResultMap集合容量2:"+combineResultMap.size());
// 合并后打印出所有内容
for (Map.Entry<String, String> entry : combineResultMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
输入结果
combineResultMap集合容量0:0
combineResultMap集合容量1:3
combineResultMap集合容量2:7
June:六月
Feb:二月
Apr:四月
May:五月
Jan:一月
July:七月
Mar:三月
这里我打印了容量,HashMap的putlAll方法还是存在多次扩容的情况,不过最终Map的容量还是比较理想。