Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum values from Java Hashmap [duplicate]

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.

like image 980
kennechu Avatar asked Feb 09 '14 21:02

kennechu


People also ask

Can Java HashMap have duplicate values?

Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

What happens if the same key is inserted twice in the HashMap?

If you try to insert the duplicate key, it will replace the element of the corresponding key. HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.

Does map in Java allow duplicates?

Map doesn't allow duplicate keys, but it allows duplicate values. HashMap and LinkedHashMap allows null keys and null values but TreeMap doesn't allow any null key or value. Map can't be traversed so you need to convert it into Set using keySet() or entrySet() method.


1 Answers

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.

like image 164
Óscar López Avatar answered Sep 19 '22 15:09

Óscar López