How to sum values from Java Hashmap [duplicate]

不羁的心 提交于 2019-12-19 05:03:59

问题


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"?

Regards and thanks for the help.


回答1:


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

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

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.




回答2:


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

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

or in this case just:

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



回答3:


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

//sum now contains the sum!

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



来源:https://stackoverflow.com/questions/21665538/how-to-sum-values-from-java-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!