How to sum values from Java Hashmap

60,101

Solution 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.

Solution 2

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...

Solution 3

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;
}
Share:
60,101
kennechu
Author by

kennechu

Updated on February 10, 2020

Comments

  • kennechu
    kennechu over 4 years

    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.

  • luksch
    luksch over 10 years
    you beat me to it! +1
  • kennechu
    kennechu over 10 years
    Thank's a lot for your time, it works and i have the result that i wanted!!
  • kennechu
    kennechu over 10 years
    Thank's a lot for your time!
  • rvazquezglez
    rvazquezglez about 8 years
    In java 8 you can do map.values().stream().sum()