Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# merging two HashMaps

manish ahuja
Ranch Hand
Posts: 312
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

Sheriff
Posts: 14691
16
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
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.