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
Vinay_guptaVinay_gupta 

Map Filling inside For Loop

Hi All,
I am net to Map and need ur help here.

Can anyone help me how to fill value in Map in below example. Can you please help me with the Code?

Map<id,List<Contacts>> CustMap = new Map<Id,List<Contacts>>;

for(Account ac:[SELECT id,name,(SELECT id FROM Contacts) FROM Account])
{
How to fill Map here where Id would be Account Id and Values would be list of Contacts.?
}

Regards,
Varun
 
Best Answer chosen by Vinay_gupta
Amit Chaudhary 8Amit Chaudhary 8
Please update your code like below
 
Map<id,List<Contacts>> CustMap = new Map<Id,List<Contacts>>();

for(Account ac:[SELECT id,name,(SELECT id FROM Contacts) FROM Account] )
{
	List<Contact> lstCont = ac.Contacts;
	CustMap.put(ac.id, lstCont);
}

Let us know if this will help you
 

All Answers

WEN JIEWEN JIE
Hi, 
Try this one.

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

for(Account ac:[SELECT id,name,(SELECT id FROM Contacts) FROM Account limit 5])
{
    CustMap.put(ac.Id, ac.contacts);
}
Ajay K DubediAjay K Dubedi

Hi Varun,

Please try this hope it will help you.

Map<id,List<Contacts>> CustMap = new Map<Id,List<Contacts>>();
for(Account ac:[SELECT Id,name,(SELECT id FROM Contacts) FROM Account])
{
	if(!CustMap.containsKey(ac.Id)){
		list<Contact> emptyList = new list<Contact>();
		CustMap.put(ac.Id, emptyList);
	}
	CustMap.get(ac.Id).addAll(ac.contacts);
}


Mark as a best if it help you.

Regards,

Ajay

Amit Chaudhary 8Amit Chaudhary 8
Please update your code like below
 
Map<id,List<Contacts>> CustMap = new Map<Id,List<Contacts>>();

for(Account ac:[SELECT id,name,(SELECT id FROM Contacts) FROM Account] )
{
	List<Contact> lstCont = ac.Contacts;
	CustMap.put(ac.id, lstCont);
}

Let us know if this will help you
 
This was selected as the best answer