/**
* 合并多个 Map 中相同键的值
*
* @param maps 多个 Map
* @return 合并后的 Map
*/
public static Map<String, Integer> sumValues(Map<String, Integer>... maps) {
Map<String, Integer> result = new HashMap<>();
for (Map<String, Integer> map : maps) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
// 如果结果中已经包含该键,则累加值,否则添加新键值对
result.merge(key, value, Integer::sum);
}
}
return result;
}
测试代码
@Test
public void test1() {
HashMap<String, Integer> hashMap = new HashMap<String, Integer>() {{
put("a", 1);
put("b", 2);
}};
HashMap<String, Integer> hashMap2 = new HashMap<String, Integer>() {{
put("a", 3);
put("b", 4);
}};
Map<String, Integer> stringIntegerMap = sumValues(hashMap, hashMap2);
System.out.println(stringIntegerMap);
}
结果值返回 {a=4, b=6}
评论区