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 Answers 3

4

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

2
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);
1
  • 1
    I suggest you to add few details in words to the answer Commented Apr 11, 2018 at 11:43
-1

public map<Id,List> mapAccCon = new map<id,List>();

List lstAccount = [SELECT Id, (SELECT Id, Name FROM Contacts) FROM Account where id='00100000000ABCD'];

for(Account lstAcc : lstAccount) { mapAccCon.put(lstAcc.id, lstAcc.Contacts); }

System.debug(mapAccCon);

1
  • This doesn't even attempt to answer the question, and is a code dump. The explanation is as important as the rest of the answer.
    – Derek F
    Commented Mar 3, 2022 at 12:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .