1.11M Members

Maps, can you add values together?

 
0
 

Ok, so I am not sure how to do this but I am sure it can be done. Here is a scenario:

I am reading in a text file that has a persons name and then the salary that they make per year for their job. The text file may look something like this:

David $30,000
Sean $40,000
Greg $70,000
Bill $55,000
David $25,000
Greg $20,000

I want to use a TreeMap to organize this so that it lists the people in alpha order. I know how to read in the text file and I write the Map as follows:

Map<String, Double> pplsWages = new TreeMap<String, Double>();

propIdValues.put(name, wage);

The actual code is longer but I don't think there is a need to write it because it all works. As you know, when this gets printed out it will display:

David $25,000
Sean $40,000
Greg $20,000
Bill $55,000

This is not what I want to happen. I want it to display David as having a wage of $55,000 and Greg as having a wage of $90,000. I want to be able to add the values together if the key is the same. I have searched around but have not come up with any answers. Any help would be much appreciated! Thanks in advance!

 
0
 

Maps do not sum the values as you add entries, the old value is just replaced by the new one when you call put() for the same key.

you'll have to compute the sums by yourself :

Integer oldWage = propIdValues.get(name);
   oldWage = oldWage == null ? 0 : oldWage;
   propIdValues.put(name, oldWage + wage);
 
0
 

CrazyDieter, sorry that it took so long to get back to you, thank you very much for answering my question and by providing the code needed. You rock! Thanks again!

Question Answered as of 4 Years Ago by CrazyDieter
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article