# Running Total by Key Group in HashMap

• 11-16-2009, 04:20 PM
KevMull
Running Total by Key Group in HashMap
How do I keep a running total on each key in my hashMap?

I'm looping through a database table of categories (Integers which will be duplicate) and their price value.

I need to keep a 'ruuning price total for each category

Example...

Map<Integer, Double> map = new HashMap<Integer, Double>();

map.put(new Integer(1), 1.00);
map.put(new Integer(2), 2.00);
map.put(new Integer(3), 3.00);
map.put(new Integer(1), 1.50);
map.put(new Integer(2), 2.50);
map.put(new Integer(3), 3.50);

So when I come to iterate through the above...

Key 1 would have a value of 2.50, 2 would be 4.50 and 3 would jave a value of 6.50
• 11-16-2009, 04:22 PM
PhHein
If it's not in the map add it. If it's there get the value add the amount, remove the old key value pair, then add the key with the new sum again.
• 11-16-2009, 04:26 PM
JosAH
Don't just put a new association in your Map but check if there was a previous association; if so, do this:

Code:

```Double d= map.put(yourInt, yourDouble); if (d != null) // put a new sum in the map   map.put(yourInt, yourDouble+d);```
kind regards,

Jos
• 11-16-2009, 04:44 PM
KevMull
Thanks for the quick replies guys.

JosAH, your code worked a treat

Many Thanks