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:
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.
No comments:
Post a Comment