Results 1 to 4 of 4
  1. #1
    KevMull is offline Member
    Join Date
    Nov 2009
    Posts
    2
    Rep Power
    0

    Default 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. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default

    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

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,728
    Blog Entries
    7
    Rep Power
    21

    Default

    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. #4
    KevMull is offline Member
    Join Date
    Nov 2009
    Posts
    2
    Rep Power
    0

    Default

    Thanks for the quick replies guys.

    JosAH, your code worked a treat

    Many Thanks

Similar Threads

  1. Total noob
    By J_Walker in forum New To Java
    Replies: 9
    Last Post: 04-24-2009, 04:10 AM
  2. Need Help for coding invoice total
    By maxb in forum New To Java
    Replies: 3
    Last Post: 11-22-2008, 05:22 PM
  3. total beginner needs little help
    By asambasamba in forum New To Java
    Replies: 1
    Last Post: 06-18-2008, 06:33 PM
  4. Total Newbie, Be Kind :)
    By dazza-s in forum New To Java
    Replies: 11
    Last Post: 04-26-2008, 11:54 PM
  5. Printing total out
    By denisdoherty in forum New To Java
    Replies: 1
    Last Post: 04-25-2008, 07:40 AM

Posting Permissions

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