'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 1:[1]
The method that Josh provided works fine. If you'd like to remove one line of code, you can using the following approach:
Map<Id, Map<Id,Addendum__c>> addendums = new Map<Id,Map<Id,Addendum__c>>();
for(Addendum__c addendum : [SELECT Id,Opportunity__c FROM Addendum__c WHERE Opportunity__c IN :oppBatch]){
addendums.put(addendum.opportunity__c, new Map<Id, Addendum__c>{addendum.id => addendum});
}
I'm not aware of a more efficient approach than this one.
Solution 2:[2]
I found a way to do this, although I'm not sure whether it's the most efficient method or not. So if you have a better solution, please let me know, I'll transfer the "solution" credit to you.
What I did was assign the first map, and then place that map within the final map.
// 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]){
Map<Id,Addendum__c> thisAddendum = new Map<Id,Addendum__c>{ addendum.Id => addendum };
addendums.put(addendum.Opportunity__c,thisAddendum);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | VictorKilo |
