function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MY DEV_SANDBOXMY DEV_SANDBOX 

we have to define a map ..., for that key is account id and values are account related contacts

we have to define a map ..., for that key is account id and values are account related contacts
GouthamGoutham
Hi,
Load the map as following
Map<id,list<contact>> accountRelatedContacts = new Map<id,list<contact>>();

for(Account acc : [select id,(select id from contacts) from Account]){
	if(accountRelatedContacts.get(acc.id)==null)
		accountRelatedContacts.put(acc.id,new list<contact>{});
	if(accountRelatedContacts.get(acc.id)!=null)
		accountRelatedContacts.get(acc.id).addAll(acc.contacts);
}

 
Abhishek BansalAbhishek Bansal
Hi,

You can use the below sample code :
Set<Id> accountIdsSet = new Set<Id>(); //This set will contain the id of accounts for which you want to create the map.

Map<Id,List<Contact>> mapOfAccountIdWithContacts = new Map<Id,List<Contact>>();

for(Account acc : [Select id, (Select id from Contacts) from Account where ID IN :accountIdsSet]){
	List<Contact> conList = new List<Contact>();
	conList.addAll(acc.Contacts);
	mapOfAccountIdWithContacts.put(acc.id, conList);
}

//Now this map mapOfAccountIdWithContacts will contain the account id with list of child contacts


Please let me know if you need any further help on this.

Thanks,​
Abhishek Bansal.

Amit Chaudhary 8Amit Chaudhary 8
Please check below post for map
1 ) http://amitsalesforce.blogspot.com/2016/09/collection-in-salesforce-example-using.html


Example 1:-
Map<Id,Account> mapAccount = new Map<Id,Account>([ Select id, (Select id from Contacts) from Account  limit 10]);

for(String strAccId : mapAccount.ketSet() )
{
    System.debug('------strAccId----->'+strAccId);
    Account acc = mapAccount.get(strAccId);
    for(Contact cont :acc.Contacts )
    {
        System.debug('----cont.id------->'+cont.id);
    }
}

Example 2:-
List<Account> lstAcc =[ Select id, (Select id from Contacts) from Account limit 10 ] ;
Map<Id,List<Contact>> mapAccount = new Map<Id,List<Contact>>();

for(Account acc : lstAcc)
{
    mapAccount.put(acc.id, acc.Contacts);
}

Example 3:-
trigger ContactTriggerWithMap on Contact (before insert) 
{
    Set<Id> SetAccountId = new Set<Id>();
    for(Contact cont: Trigger.new) 
 {
        if(cont.AccountId != null) 
  {
            SetAccountId.add(cont.AccountId);
        }
    }
    
    if(SetAccountId.size() > 0 ) 
 {
        Map<Id, Account> mapAccount = new Map<Id, Account>([Select Id, Name, Type from Account where Id IN :SetAccountId ]);
        for(Contact cont: Trigger.new) 
  {
            if(cont.AccountId != null && mapAccount.containsKey(cont.AccountId) ) 
   {
                cont.Type__c = mapAccount.get(cont.AccountId).Type;
            }
        }
    }
}


Let us know if this will help you