Merging two maps

Given a map and the apex map method putAll()

map<String,Integer> intsByKey = new map<String,Integer> 
   {'a' => 1, 'b' => 2};
intsByKey.putAll(new map<String,Integer> 
   {'c' => 3, 'd' => 4, 'a' => 10});

The documentation states that putAll replaces the contents of the target map

The new mappings from fromMap replace any mappings that the original
map had.

So, how does one merge two maps in a convenient way?

Answer

Well, conveniently for us, the documentation is misleading/ambiguous and putAll does a true merge.

map<String,Integer> intsByKey = new map<String,Integer> 
   {'a' => 1, 'b' => 2};
intsByKey.putAll(new map<String,Integer> 
   {'c' => 3, 'd' => 4, 'a' => 10});

The value of intsByKey after the second statement is:

{a=10, b=2, c=3, d=4}

That is, putAll acts like addAll does for lists/sets

Props to Scott Hung’s blog for saving me the trouble of writing a for loop

Attribution
Source : Link , Question Author : cropredy , Answer Author : cropredy

Leave a Comment