This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

merging two HashMaps

 
manish ahuja
Ranch Hand
Posts: 312
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am looking for a way to merge the elements of two HashMaps.
Here is the scenario there are two hashmaps both containing custom objects as its elements

The custom object is something like this

class Custom {

String level; // can be values "high" or "low"
String name;
int sum;

}


The elements are like this

Hashmap1 (all elements will belong to level=High)
{name=ABC, sum=10, level=HIGH}
{name=XYZ, sum=15, level=HIGH}
{name=PQR, sum=20, level=HIGH}

Hashmap2 (all elements will belong to level=Low)
{name=LMN, sum=11, level=LOW}
{name=XYZ, sum=25, level=LOW}
{name=UVW, sum=30, level=LOW}

I want to create a single hashmap merging the elements of the above two hashmaps adding up the values of the common elements something like this

CompositeHashmap
//all Level HIGH multiply by 2
{name=ABC, sum=10*2}
{name=PQR, sum=20*2}
//all Level LOW multiply by 3
{name=LMN, sum=11*3}
{name=UVW, sum=30*3}
// for the common elements add up the product values of each level
{name=XYZ, sum=15*2 + 25 *3}


Could you let me know your thoughts on how to proceed on the same.


Thanks
 
Christophe Verré
Sheriff
Pie
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A simple approach would be :
. Make a new Map
. Loop through the HIGH map
. Register every item of the HIGH map, adjusting the sum
. Loop through the LOW map
. Check if the key is already in the new map.
. If it is, get it, and adjust the sum.
. If it isn't, register item of the LOW map, adjusting the sum
 
Himanshu Gupta
Ranch Hand
Posts: 598
Android Eclipse IDE Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whats the problem? You can write the code to do all you aim at in a single class and use it. I hope that you are using which is a String as a Key for this Map.

 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic