Results 1 to 4 of 4
- 11-16-2009, 03:20 PM #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
- 11-16-2009, 03:22 PM #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.
Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
The Ubiquitous Newbie Tips
- 11-16-2009, 03:26 PM #3
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,380
- Blog Entries
- 7
- Rep Power
- 17
Don't just put a new association in your Map but check if there was a previous association; if so, do this:
kind regards,Java Code:Double d= map.put(yourInt, yourDouble); if (d != null) // put a new sum in the map map.put(yourInt, yourDouble+d);
Jos
- 11-16-2009, 03:44 PM #4
Member
- Join Date
- Nov 2009
- Posts
- 2
- Rep Power
- 0
Similar Threads
-
Total noob
By J_Walker in forum New To JavaReplies: 9Last Post: 04-24-2009, 03:10 AM -
Need Help for coding invoice total
By maxb in forum New To JavaReplies: 3Last Post: 11-22-2008, 04:22 PM -
total beginner needs little help
By asambasamba in forum New To JavaReplies: 1Last Post: 06-18-2008, 05:33 PM -
Total Newbie, Be Kind :)
By dazza-s in forum New To JavaReplies: 11Last Post: 04-26-2008, 10:54 PM -
Printing total out
By denisdoherty in forum New To JavaReplies: 1Last Post: 04-25-2008, 06:40 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks