如何对 Java Hashmap 中的值求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21665538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:56:54  来源:igfitidea点击:

How to sum values from Java Hashmap

javacollectionshashmap

提问by kennechu

I need some help, I'm learning by myself how to deal with maps in Java ando today i was trying to get the sum of the values from a Hashmap but now Im stuck.

我需要一些帮助,我正在自学如何在 Java 中处理地图 ando 今天我试图从 Hashmap 中获取值的总和,但现在我卡住了。

This are the map values that I want to sum.

这是我想要求和的地图值。

HashMap<String, Float> map = new HashMap<String, Float>();

map.put("First Val", (float) 33.0);
map.put("Second Val", (float) 24.0);

Ass an additional question, what if I have 10 or 20 values in a map, how can I sum all of them, do I need to make a "for"?

另一个问题,如果我在地图中有 10 个或 20 个值怎么办,我如何将所有值相加,我需要做一个“for”吗?

Regards and thanks for the help.

问候并感谢您的帮助。

采纳答案by óscar López

If you need to add allthe values in a Map, try this:

如果您需要在 a 中添加所有Map,请尝试以下操作:

float sum = 0.0f;
for (float f : map.values()) {
    sum += f;
}

At the end, the sumvariable will contain the answer. So yes, for traversing a Map's values it's best to use a forloop.

最后,sum变量将包含答案。所以是的,为了遍历 aMap的值,最好使用for循环。

回答by luksch

Float sum = 0f;
for (Float val : map.values()){
    sum += val;
}

//sum now contains the sum!

A forloop indeed serves well for the intended purpose, although you could also use a while loop and an iterator...

一个for循环的确很适合在预期目的,但你也可以使用一个while循环和迭代器...

回答by Kuba Spatny

You can definitely do that using a for-loop. You can either use an entry set:

您绝对可以使用for-loop. 您可以使用条目集:

for (Entry<String, Float> entry : map.entrySet()) {
    sum += entry.getValue();
}

or in this case just:

或者在这种情况下只是:

for (float value : map.values()) {
    sum += value;
}