[SalesForce] How to get list of All accounts and their contacts in one soql and store in a map

I want to create a Map (collection), which has Account as a Key and list of contacts as value.

I am able to create this by getting list of accounts with contacts and then iterating each account and manually adding in the Map collection as below code.

public map<Account,List<Contact>> accountContactMap = new map<Account,List<Contact>>();

List<Account> lstAccount = [SELECT Id, name, (SELECT Id, Name FROM Contacts) FROM Account];

for(Account acc : lstAccount)
{
    this.accountContactMap.put(acc, acc.Contacts);
}

System.debug(this.accountContactMap);

Is there any way to create this map directly from soql query instead of iterating each account and manually adding to map as below :

public map<Account,List<Contact>> accountContactMap = ['soql query'];

Best Answer

You can only get a Map <Id, SObject> (Account Id => Record) when you directly assign a query result into a map (use a query in the map constructor).

Map <Id, Account> allAccounts = new Map <Id, Account> ([SELECT Id, name, (SELECT Id, Name FROM Contacts) FROM Account]);

Related Topic