# Thread: Running Total by Key Group in HashMap

1. Member
Join Date
Nov 2009
Posts
2
Rep Power
0

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

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

3. Don't just put a new association in your Map but check if there was a previous association; if so, do this:

Java 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

4. Member
Join Date
Nov 2009
Posts
2
Rep Power
0
Thanks for the quick replies guys.

JosAH, your code worked a treat

Many Thanks

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•