如何总结Java Hashmap的值 [英] How to sum values from Java Hashmap
本文介绍了如何总结Java Hashmap的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一些帮助,我自己学习如何处理地图在Java ando今天,我试图获得的值从Hashmap的总和,但现在Im卡住。
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.
这是我想要求和的映射值。
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"?
感谢您的帮助。
推荐答案
如果您需要在地图
中添加全部值,请尝试:
If you need to add all the values in a Map
, try this:
float sum = 0.0f;
for (float f : map.values()) {
sum += f;
}
最后, sum
变量将包含答案。所以是的,对于遍历 Map
的值,最好使用 for
循环。
At the end, the sum
variable will contain the answer. So yes, for traversing a Map
's values it's best to use a for
loop.
这篇关于如何总结Java Hashmap的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文