Ad
Ad
Ad
Beginner Dev

Dev Tip1: Populate Map with List of values in Apex/Salesforce

Pinterest LinkedIn Tumblr

In this post, We will try to populate Map with List of Values. Whether we write a trigger, Apex class, or Batch Apex we encounter this Scenario.

Scenario 1:
We want to populate a Map with Account Id as the key and List of Contacts as Values. We will be iterating against the contact object and populating this map.

Note: We are populating a Map with List of Subject.

Map> AccountIdToContacts = new Map>();

for(Contact newCont : [SELECT AccountId FROM Contact LIMIT 50000]) {
if(AccountIdToContacts.containsKey(newCont.AccountId)) {
List conts = AccountIdToContacts.get(newCont.AccountId);
conts.add(newCont);
AccountIdToContacts.put(newCont.AccountId, conts);
} else {
AccountIdToContacts.put(newCont.AccountId, new List { newCont });
}
}

Scenario 2:
We want to populate a Map with Account Id as the key and List of Opportunities as Values.
We will be iterating against the Opportunity object and populating this map.
Note: We are populating a Map with List of String.

Map> AccountIdToOppIds = new Map>();
for(Opportunity newOpp : [SELECT AccountId FROM Opportunity LIMIT 50000]) {
if(AccountIdToOppIds.containsKey(newOpp.AccountId)) {
List oppIds = AccountIdToOppIds.get(newOpp.AccountId);
oppIds.add(newOpp);
AccountIdToOppIds.put(newOpp.AccountId, oppIds);
} else {
AccountIdToOppIds.put(newOpp.AccountId, new List { newOpp.Id });
}
}


Write A Comment