如何轻松对两个 hashMap<String,Integer> 求和?

how to easily sum two hashMaplt;String,Integergt;?(如何轻松对两个 hashMapString,Integer 求和?)

本文介绍了如何轻松对两个 hashMap<String,Integer> 求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 HashMap<String,Integer>

我怎样才能轻松地总结它们?

How can I sum them easily?

意味着对于字符串a",键将是(来自 Map1 的值 + 来自 Map2 的值)的总和?

Meaning that for String "a" the key will be sum of (value from Map1 + value from Map2)?

我可以迭代 Map2 的每个项目并手动添加到 Map1.

I can iterate every item of Map2 and add manually to Map1.

但认为可能有更简单的方法吗?

But thought there might be an easier way?

我更喜欢将整数相加到其中一张地图中.不创建一个新的

I prefer summing the Integers into one of the maps. Not creating a new one

推荐答案

由于 Java 8 Map 包含 merge 方法需要

Since Java 8 Map contains merge method which requires

  • 键,
  • 新值,
  • 以及用于决定在地图中放入什么值的函数如果它已经包含我们的键(将根据旧值和新值做出决定).
  • key,
  • new value,
  • and function which will be used to decide what value to put in map if it already contains our key (decision will be made based on old and new value).

所以你可以简单地使用:

So you could simply use:

map2.forEach((k, v) -> map1.merge(k, v, Integer::sum));

现在您的 map1 将包含 map2 中的所有值,如果键相同,旧值将添加到新值中,结果将存储在 map 中.

Now your map1 will contain all values from map2 and in case of same keys old value will be added to new value and result will be stored in map.

演示:

Map<String, Integer> m1 = new HashMap<>();
m1.put("a", 1);
m1.put("b", 2);
Map<String, Integer> m2 = new HashMap<>();
m2.put("a", 3);
m2.put("c", 10);

System.out.println(m1);
System.out.println(m2);

//iterate over second map and merge its elements into map 1 using 
//same key and sum of values
m2.forEach((k, v) -> m1.merge(k, v, Integer::sum));

System.out.println("===========");
System.out.println(m1);

输出:

{a=1, b=2}
{a=3, c=10}
===========
{a=4, b=2, c=10}

这篇关于如何轻松对两个 hashMap<String,Integer> 求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何轻松对两个 hashMap<String,Integer> 求和?

基础教程推荐