To create a Map of AccountId and List of Contacts in Apex, you can use the following code:
Map<Id, List<Contact>> accountContactsMap = new Map<Id, List<Contact>>();
for (Contact c : [SELECT AccountId,Id,FirstName,LastName FROM Contact]) {
if (!accountContactsMap.containsKey(c.AccountId)) {
accountContactsMap.put(c.AccountId, new List<Contact>{c});
} else {
accountContactsMap.get(c.AccountId).add(c);
}
}
This code creates an empty map called accountContactsMap and then queries the Contact object to get a list of all Contact records. It then iterates through the list of Contacts and adds each Contact to the map, using the AccountId as the key and the Contact as the value. If the AccountId is already present in the map, it adds the Contact to the list of Contacts associated with that AccountId.
You can then access the list of Contacts for a particular AccountId by using the get method of the map, like this:
List<Contact> contactsForAccount = accountContactsMap.get(accountId);

Leave a comment