如何合并多个hashmaps也总结了java中同一个键的值 [英] how to merge more than one hashmaps also sum the values of same key in java

查看:114
本文介绍了如何合并多个hashmaps也总结了java中同一个键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



<$ p我想要合并多个hashmaps也可以合计同一个键的值,
我想用下面的玩具示例来解释我的问题$ p> HashMap< String,Integer> m = new HashMap<>();
HashMap< String,Integer> m2 = new HashMap<>();

m.put(apple,2);
m.put(pear,3);
m2.put(apple,9);
m2.put(banana,6);

ı尝试了putall



m.putAll (m2);

输出如下
{banana = 6,apple = 9,pear = 3}

但其结果不适用于此问题。
我想输出为

香蕉= 6苹果= 11梨= 3

如果你使用的是Java 8,你可以使用新的 如何在java中获得这个结果? href =http://docs.oracle.com/javase/8/docs/api/java/util/Map.html#merge-KV-java.util.function.BiFunction-> merge 方法(k,v) - > m.merge(k,v,(v1,v2) )→> v1 + v2));


ı am trying to merge more than one hashmaps also sum the values of same key, ı want to explain my problem with toy example as follows

    HashMap<String, Integer> m = new HashMap<>();
    HashMap<String, Integer> m2 = new HashMap<>();

    m.put("apple", 2);
    m.put("pear", 3);
    m2.put("apple", 9);
    m2.put("banana", 6);

ı tried putall

m.putAll(m2);

output is as follows {banana=6, apple=9, pear=3}

but its result is not true for this problem. ı want to output as

{banana=6, apple=11, pear=3}

how can ı get this result in java?

解决方案

If you are using Java 8, you can use the new merge method of Map.

m2.forEach((k, v) -> m.merge(k, v, (v1, v2) -> v1 + v2));

这篇关于如何合并多个hashmaps也总结了java中同一个键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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