Take the 2-minute tour ×

I need to copy all keys and values from one A HashMap onto another one B, but not to replace existing keys and values.

Whats the best way to do that?

I was thinking instead iterating the keySet and checkig if it exist or not, I would

Map temp = new HashMap(); // generic later
share|improve this question

3 Answers 3

up vote 26 down vote accepted

It looks like you are willing to create a temporary Map, so I'd do it like this:

Map tmp = new HashMap(patch);

Here, patch is the map that you are adding to the target map.

share|improve this answer
+1 pretty cool :) –  Fabian Barney Aug 25 '11 at 17:53
In this case you don't need to do removeAll since they'll get overriden anyways. –  Reverend Gonzo Aug 25 '11 at 18:26
@Reverend Gonzo: Overwritten by what? –  erickson Aug 25 '11 at 18:34
Never mind I read that wrong –  Reverend Gonzo Aug 25 '11 at 23:06
Would not map.clear(); map.putAll(newMap) work ? –  luksmir Jun 13 '13 at 7:51

Using Guava's Maps class' utility methods to compute the difference of 2 maps you can do it in a single line, with a method signature which makes it more clear what you are trying to accomplish:

public static void main(final String[] args) {
    // Create some maps
    final Map<Integer, String> map1 = new HashMap<Integer, String>();
    map1.put(1, "Hello");
    map1.put(2, "There");
    final Map<Integer, String> map2 = new HashMap<Integer, String>();
    map2.put(2, "There");
    map2.put(3, "is");
    map2.put(4, "a");
    map2.put(5, "bird");

    // Add everything in map1 not in map2 to map2
    map2.putAll(Maps.difference(map1, map2).entriesOnlyOnLeft());
share|improve this answer
Beautiful. That is. –  rapadura Aug 25 '11 at 18:26

Just iterate and add:

for(Map.Entry e : a.entrySet())
    b.put(e.getKey(), e.getValue());

Edit to add:

If you can make changes to a, you can also do:


and a will have exactly what you need. (all the entries in b and all the entries in a that aren't in b)

share|improve this answer
1.) entrySet() returns a Set<Map.Entry>. 2.) There is no method contains(...)for java.util.Map. –  Fabian Barney Aug 25 '11 at 17:39
Isnt there a smarter way? Like a Collections utility or so? I hate all the for loops everywhere. –  rapadura Aug 25 '11 at 17:39
Oh and also this is legacy code so no generics... –  rapadura Aug 25 '11 at 17:40
@Fatal: edit: changed contains() to containsKey() –  Reverend Gonzo Aug 25 '11 at 17:43
@AntonioP: All the for loops everywhere? There's one for loop and it's about as straightforward as you can get. –  Reverend Gonzo Aug 25 '11 at 17:44

Your Answer


