本文介紹了如何合并多個hashmaps還對java中相同鍵的值求和的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試合并多個哈希圖也對相同鍵的值求和,我想用玩具示例解釋我的問題如下
? 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);
我試過putall
m.putAll(m2);
m.putAll(m2);
輸出如下{香蕉=6,蘋果=9,梨=3}
output is as follows {banana=6, apple=9, pear=3}
但它的結果不適用于這個問題.我想輸出為
but its result is not true for this problem. ? want to output as
{香蕉=6,蘋果=11,梨=3}
{banana=6, apple=11, pear=3}
我如何在 java 中得到這個結果?
how can ? get this result in java?
推薦答案
如果你使用的是Java 8,你可以使用新的merge Map的方法.
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中相同鍵的值求和的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!