This week's book giveaway is in the Agile forum.
We're giving away four copies of The Software Craftsman and have Sandro Mancuso on-line!
See this thread for details.
The moose likes Java in General and the fly likes merging two HashMaps Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "merging two HashMaps" Watch "merging two HashMaps" New topic

merging two HashMaps

manish ahuja
Ranch Hand

Joined: Oct 23, 2003
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

//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.

Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

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

[My Blog]
All roads lead to JavaRanch
Himanshu Gupta
Ranch Hand

Joined: Aug 18, 2008
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.

My Blog SCJP 5 SCWCD 5
I agree. Here's the link:
subject: merging two HashMaps