Here's an example code snippet in Apex that retrieves a map of account IDs and their corresponding list of contacts:
Map<Id, List<Contact>> accountContactsMap = new Map<Id, List<Contact>>();
List<Contact> allContacts = [SELECT Id, AccountId FROM Contact];
for(Contact c : allContacts){
if(accountContactsMap.containsKey(c.AccountId)){
accountContactsMap.get(c.AccountId).add(c);
}
else{
accountContactsMap.put(c.AccountId, new List<Contact>{c});
}
}
In this example, we first create a Map that will store Account IDs as keys and lists of associated Contact records as values.
We then query all Contact records and iterate through them using a for loop. For each Contact, we check if the AccountID is already a key in the accountContactsMap using the containsKey() function. If it is, we add the Contact to the existing list of contacts for that account using the add() function. If it's not, we create a new list containing the current Contact and add it to the map using the put() function.
After the loop completes, the accountContactsMap will contain all Account IDs as keys and lists of their associated Contact records as values.
No comments:
Post a Comment