15

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?

1 Answer 1

22

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

6
  • 2
    I think you misunderstood the statement (it's kind of ambiguous). What it's saying is that if a particular key is already in both maps, the one in the map you call putAll on will gain the new value.
    – sfdcfox
    Commented Jun 25, 2018 at 22:41
  • 2
    Thinking about it, make sure you leave feedback on that page for the documentation team; they need to fix it, because it's clearly misleading.
    – sfdcfox
    Commented Jun 25, 2018 at 22:44
  • 3
    The statement makes sense, ONLY AFTER, you realize what it is doing lol
    – Eric
    Commented Jun 25, 2018 at 22:48
  • 1
    actually, I have to agree with @sfdcfox - had I read the doc example more carefully, then I would see that it does what one wants.
    – cropredy
    Commented Jun 25, 2018 at 22:59
  • Ahh yes. I did not look at the example. With that context it does make sense.
    – Eric
    Commented Jun 26, 2018 at 0:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .