(Java)的HashMap组 [英] HashMap group by (Java)
本文介绍了(Java)的HashMap组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以按Key进行分组,并将值添加到Java的HashMap中
Is there a way we can group by Key and add the value in a HashMap in Java
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("A", 2);
map.put("A", 3);
map.put("B", 4);
map.put("A", 5);
map.put("B", 4);
结果是
The result is
A = 10
B = 8
任何帮助都会有所帮助!!!
Any help would be helpful !!!
推荐答案
编写这样做的实用程序方法:
Write utility method that does this:
Map<String, Integer> map = new HashMap<>();
.........
public void putAndIncrement(String key, int value) {
Integer prev = map.get(key);
Integer newValue = value;
if (prev != null) {
newValue += prev.intValue();
}
map.put(newValue);
}
这篇关于(Java)的HashMap组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文