Search code examples
triggerssalesforceapex-code

Apex Map within a Map


I need to have a Map within a Map in one of my Triggers. I know how to build the map initially as that is documented:

Map<Id, Map<Id, Addendum__c>> addendums = new Map<Id, Map<Id, Addendum__c>>{};

However, I'm having trouble actually assigning values to the multi-dimensional map. Normally I would use .put() to place values into a single-dimension map. Maybe I'm still supposed to use that function, but I can't for the life of me figure out the correct syntax.

I have tried the following which do not work:

addendums.put(addendum.Opportunity__c, addendum.Id, addendum);

addendums.put(addendum.Opportunity__c, (addendum.Id, addendum));

Does anyone know how to do this?

Thanks!


Solution

  • Using your sample code will work, though of course the second level map can only ever have one entry, if you're in a situation where you may need more then the code below will do the trick for you:

        // This line creates the map in the proper format
        Map<Id,Map<Id,Addendum__c>> addendums = new Map<Id,Map<Id,Addendum__c>>{};
        
        // This for loop goes through each addendum and first places it into a single dimension map.  
        // Once that map is created, it is placed into the final multi-dimensional
        for(Addendum__c addendum : [SELECT Id,Opportunity__c FROM Addendum__c WHERE Opportunity__c IN :oppBatch])
        {
            if(addendums.get(addendum.Opportunity__c) == null)
            {
                addendums.put(addendum.Opportunity__c, new Map<Id, Addendum__c>{addendum.Id => addendum);
            }
            else
            {
                addendums.get(addendum.Opportunity__c).put(addendum.Id, addendum);
            }
        }
    

    As you can see this uses get() on the first map to get the correct second-level map in which we want to add an addendum.