Map<Id, List<Contact>> account_ContactMap = new Map<Id, List<Contact>>();
//Loop over Contact records.
for(Contact con : [SELECT Id, AccountId, Name, Email FROM Contact GroupBy AccountId])
{
//Cretae new Key for Account, if already not exist.
if(!account_ContactMap.containsKey(con.AccountId))
account_ContactMap.put(con.AccountId, new List<Contact>());
//Add Contact value for Account key.
account_contactMap.get(con.AccountId).add(con);
}
Try this one
Thank you
Ajay Dubedi
All Answers
Please make map like this
Thanks,
Gaurav
Skype: gaurav62990
error:
(Extra ']', at 'AccountId'.)
Please refer to the below code. Hope it helps you.
Please select as best answer if it helps you.
Thank You,
Ajay Dubedi
Ajay Dubedi
i have an error in this code...
(Variable does not exist: contact)
Try this one
Thank you
Ajay Dubedi
Hi Sunil,
Please try the below code Open Execute Anonymous and write this code:
Please make it best if it helps.
Thanks
Akshay
i have code like this ...
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);
but its coming an error'//
Like..
( This cannot be referenced in a static context)...
can anyone tell me?
Please refer to the 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)
{
accountContactMap.put(acc, acc.Contacts);
}
System.debug(accountContactMap);
acc is variable which will iterate for all the accounts from the list "lstAccount".So no need to use "this" in this case.
Thank You,
Ajay Dubedi