Play Games

Search This Blog

Thursday, November 19, 2015

How to prepare map of all accounts and its related contacts in apex class(map of id,list of sobject)

Suppose I want to prepare a map of all accounts and its related contact.

Map<id,List<Contact>> accountMap = new Map<id,List<Contact>> ();
List<Account> accountList =[select id,name from Account];
for(contact con:[select id,name,accountId from contact where accountId in:accountList]) {
if(accountMap.containsKey(con.accountId)) {
accountMap.get(con.accountId).add(con);
} else {
accountMap.put(con.accountId,new List<contact>{con});
}
}
system.debug('accountMapaccountMap'+accountMap);

When you run the above code snippet in workbench or developer console you will see the accountMap.
Output:

No comments:

Post a Comment