如何轻松地总结两个hashMap< String,Integer&gt ;?? [英] how to easily sum two hashMap<String,Integer>?

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

问题描述

我有两个 HashMap< String,Integer>



我怎样才能轻松地将它们求和?



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

我可以迭代Map2的每一项并手动添加到Map1中。



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

我宁愿将整数合并到一张地图中。由于Java 8 Map 包含,因此不会创建新的

href =https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#merge-KV-java.util.function.BiFunction- =nofollow noreferrer> <
$ b


  • 键,
  • $ b code $ c> merge
    方法$ b
  • 新值,
  • 以及将用于决定在map 中放置什么值的函数(如果它已包含我们的键)基于旧的和新的价值)。



所以你可以简单地使用:

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

现在您的 map1 map2 ,并且在相同键的情况下,旧值将被添加到新值并且结果将被存储在地图中。



DEMO:

 地图< 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);

//遍历第二个映射并使用
//将其元素合并到映射1中//相同的键和值的总和
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}


I have two HashMap<String,Integer>

How can I sum them easily?

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

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

解决方案

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));

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.

DEMO:

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);

Output:

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

这篇关于如何轻松地总结两个hashMap&lt; String,Integer&gt ;??的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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