BlahBlah
BlahBlah

Reputation: 275

Merge maps in java

What i'm trying to do is pretty simple.I want to merge two maps. Say

map1={(1,"one"),(2,"two"),(3,"three");
map2={(1,"onetoo"),(4,"four")};

if i follow this->

map3.putall(map1);
map3.putall(map2);

then value of 1 is onetoo but when i follow the reverse it is one. is there anyway i could change that?what i mean is that java overwrites and puts only the latest value for a key. i.e if onetoo was added after one (in their respective maps)then no matter what the order of putall calls to map3 the value remains onetoo.

Upvotes: 1

Views: 3315

Answers (3)

Ahmad
Ahmad

Reputation: 2190

Well, If your programe worked as you want, then predict the output of the following

 map3.get(1);

You could never know whether it is "One" or "Onetoo".

Too prevent any such problem, Maps in Java are designed to contain only unique keys.

So , if you write

map3.putall(map1);

the value of 1 is "one". but as soon as you write

map3.putall(map2);

the value of 1 is reset and it becomes "onetoo". reverse happens when you reverse it. Possible solutions could be.

  1. Put in your keys in maps in such a way that they (keys) uniquely identifies an object. So that whenever in future you merge maps, no clash happens(in terms of duplicity) in keys.

  2. If you can't do it, then a possible solution could be to get all keys of every map and check for duplicity and change the duplicate keys in such a way that you can retrieve your objects without hassle.

Upvotes: 0

Petar Ivanov
Petar Ivanov

Reputation: 93020

There is no way to do that, unless you store the actual time when the values were added.

Say map1={(1,("one", 15:15)), (2, ("two", 15:16))}

Then you can add all of map1 and then iterate over map2 adding only if the key is not already there or if it's there but with a earlier timestamp.

Upvotes: 7

Ed Morales
Ed Morales

Reputation: 1037

That's how maps work, they use the hashcode of the object you set as key as a way to identify its self within the map entries, and as you can see it has to be unique.

So you would have to specify another key since an integer value of 1 has a hashcode of 1.

Upvotes: 1

Related Questions