32

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.

kennechu
  • 1,412
  • 9
  • 25
  • 37
  • 4
    Insteaf of `(float) 33.0` you can use `33f` or `33.0f` – Christian Tapia Feb 09 '14 at 21:55
  • What steps would *you* do to sum a bunch of values from a collection of unknown size? Yes, a "for" or a "loop" sounds appropriate - search for it. – user2864740 Feb 09 '14 at 22:05
  • 1
    I do not think this question is a real duplicate. This is more specific. and the solution in java 8 is map.values().stream().mapToDouble(Double::doubleValue).sum() – Kuzeko Jun 18 '17 at 09:30

3 Answers3

25

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
4
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...

luksch
  • 11,497
  • 6
  • 38
  • 53
4

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;
}
Kuba Spatny
  • 26,618
  • 9
  • 40
  • 63