How to sum values from Java Hashmap

collections, hashmap, java

Solution

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.

Problem

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.

Original source

Related problems