如何轻松地将两个hashMap< String,Integer>相加? [英] how to easily sum two hashMap<String,Integer>?

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

问题描述

我有两个 HashMap< String,Integer>

我如何轻松总结它们?

意味着对于字符串"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?

我更喜欢将Integers汇总到其中一张图中.不创建新的

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

推荐答案

因为Java 8 Map 包含

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&lt; String,Integer&gt;相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆