How to add parent Id and its child records list to a map in Salesforce?

How to add parent Id and its child records list to a map in Salesforce?

Sample Code:

Map<Id, List<Contact>> mapAcctIdContactList = new Map<Id, List<Contact>>();
List<Contact> listContact = [SELECT Id, FirstName, AccountId FROM Contact];


for(Contact con : listContact) {
    if(String.isNotBlank(con.AccountId)){
        if(!mapAcctIdContactList.containsKey(con.AccountId)) {
            mapAcctIdContactList.put(con.AccountId, new List<Contact>());
        }
        mapAcctIdContactList.get(con.AccountId).add(con);
    }
}


system.debug(mapAcctIdContactList);

Cheers!!!

Leave a Reply