2

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'];
3

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]);

1
public map<Id,List<Contact>> accountContactMap = new map<id,List<Contact>>();

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

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

System.debug(this.accountContactMap);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.