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
Rajesh T 19Rajesh T 19 

How to map the child records with Parent in Map<Id, List<Child Object>> in Apex programming and what's the best practices to add it correctly ?

I could see in some scenarios developers using below code to map the child records with Parent.(e.x., Contact with Account)
for(Contact con: newcontact){
                    if(con.AccountId != null){
                        if(!maponobject.containsKey(con.AccountId)) {
                        maponobject.put(Con.AccountId, new List<Contact>());
                        } } }
but in some cases developer using the below code however the functionality is same as above,
for (Contact con: newcontact){
           if(con.AccountId != Oldcon.AccountId){
                  if(!maponobject.containsKey(con.AccountId)){
                   maponobject.put(con.AccountId, new List<Contact>{con});
                  } } }

What is difference on both code(why {con} added on second one but not in first ) and how the value is putting on the maponobject on both cases?
Best Answer chosen by Rajesh T 19
Suraj Tripathi 47Suraj Tripathi 47

Hi Rajesh,

Please find the solution. "How to map the child records with Parent in Map<Id, List<Child Object>> in Apex programming and what's the best practices to add it correctly ?"

Rajesh this is BestPractice Map which is followed by almost everyone.

Case: when you want to find Number of contact  related to account(Count contacts On Account)

List<Contact> contactList=[select id,accountid from Contact where accountid!=null];
        map<Id,List<Contact>> contactMap=new map<Id,List<Contact>>();
        for(Contact con:contactList){
            if(contactMap.containsKey(con.accountid)){
                contactMap.get(con.AccountId).add(con);
            }else{
                contactMap.put(con.AccountId,new List<Contact>{con});
            }
        }


just dry run with me. 

suppose Account "Test" has 2 contacts T1,T2

1.Initially contactMap is empty It means contactMap.containsKey(con.accountid)=false

2.it will go into the else part and put in Map, On accountid=> T1 contacts 

new List<Contact>{con} //it means very first time con object is added in the new List and it would be put on the accountId

the above code means

List<Contact> contactList=new List<Contact>();
contactList.add(con);

3.Map Has <Test accountId,List<T1>>

4.for loop again iterate and this time map is not empty,Map has accountid so it will enter in if condition

a.It will get the List and then Add T2 to the List  contactMap.get(con.AccountId).add(con);

b.Map Has <Test accountId,List<T1,T2>>

Or 

Case 2:

List<Contact> contactList=[select id,accountid from Contact where accountid!=null];
        map<Id,List<Contact>> contactMap=new map<Id,List<Contact>>();
        for(Contact con:contactList){
            if(!contactMap.containsKey(con.accountid)){
                List<Contact> conList=new List<Contact>();
                conList.add(con);
                contactMap.put(con.accountid,conList);
            }else{
                List<Contact> conList=contactMap.get(con.accountid);
                conList.add(con);
                contactMap.put(con.accountid,conList);  
          }
        }

Please let me know if you have any queries.
Please mark it as the Best Answer so that other people would take reference from it.

Thank You

All Answers

Suraj Tripathi 47Suraj Tripathi 47

Hi Rajesh,

Please find the solution. "How to map the child records with Parent in Map<Id, List<Child Object>> in Apex programming and what's the best practices to add it correctly ?"

Rajesh this is BestPractice Map which is followed by almost everyone.

Case: when you want to find Number of contact  related to account(Count contacts On Account)

List<Contact> contactList=[select id,accountid from Contact where accountid!=null];
        map<Id,List<Contact>> contactMap=new map<Id,List<Contact>>();
        for(Contact con:contactList){
            if(contactMap.containsKey(con.accountid)){
                contactMap.get(con.AccountId).add(con);
            }else{
                contactMap.put(con.AccountId,new List<Contact>{con});
            }
        }


just dry run with me. 

suppose Account "Test" has 2 contacts T1,T2

1.Initially contactMap is empty It means contactMap.containsKey(con.accountid)=false

2.it will go into the else part and put in Map, On accountid=> T1 contacts 

new List<Contact>{con} //it means very first time con object is added in the new List and it would be put on the accountId

the above code means

List<Contact> contactList=new List<Contact>();
contactList.add(con);

3.Map Has <Test accountId,List<T1>>

4.for loop again iterate and this time map is not empty,Map has accountid so it will enter in if condition

a.It will get the List and then Add T2 to the List  contactMap.get(con.AccountId).add(con);

b.Map Has <Test accountId,List<T1,T2>>

Or 

Case 2:

List<Contact> contactList=[select id,accountid from Contact where accountid!=null];
        map<Id,List<Contact>> contactMap=new map<Id,List<Contact>>();
        for(Contact con:contactList){
            if(!contactMap.containsKey(con.accountid)){
                List<Contact> conList=new List<Contact>();
                conList.add(con);
                contactMap.put(con.accountid,conList);
            }else{
                List<Contact> conList=contactMap.get(con.accountid);
                conList.add(con);
                contactMap.put(con.accountid,conList);  
          }
        }

Please let me know if you have any queries.
Please mark it as the Best Answer so that other people would take reference from it.

Thank You

This was selected as the best answer
Suraj Tripathi 47Suraj Tripathi 47

You can find the Number of Contacts on Account Like this

for(Id id1:contactMap.keySet()){
            system.debug('AccountId::'+id1+' ===> '+'Number Of Contacts::'+contactMap.get(id1).size());
        }
 

 

AbhinavAbhinav (Salesforce Developers) 
HI Rajesh,

Try with debug log you will get better understanding.

In first Case you are just creating a Map with Key as AccountId but Vaue as empty contact list. Based on your business requirement you can add value to you map later on.

1st Case
Map<Id, List<Contact>> maponobject = new Map<Id, List<Contact>>();
    
    List<Contact> newcontact = new List<Contact>();
newcontact = [select Id,AccountId from Contact limit 10];
//System.debug('-------'+newcontact);
for(Contact con: newcontact){
    if(con.AccountId != null){
        if(!maponobject.containsKey(con.AccountId)) {
            maponobject.put(Con.AccountId, new List<Contact>());
        } } }

System.debug('1st Case'+maponobject);

2nd case

In second case you are adding value to map there itself i.e for every accountId you are adding contact associated with it as value.
 
Map<Id, List<Contact>> maponobject = new Map<Id, List<Contact>>();
    
    List<Contact> newcontact = new List<Contact>();
newcontact = [select Id,AccountId from Contact limit 10];
//System.debug('-------'+newcontact);
for(Contact con: newcontact){
    if(con.AccountId != null){
        if(!maponobject.containsKey(con.AccountId)) {
            maponobject.put(Con.AccountId, new List<Contact>{con});
        } } }

System.debug('2st Case'+maponobject);


Suppose for your 1st scenario later you want to add value. you can write your logic something similar to this.
for(Contact c: testContactList)
{
    if(c.AccountId != null)
    {
    maponobject.get(c.AccountId).add(c);
    }
}

System.debug('1st case after adding value '+maponobject);




Hope this answer was helpful. Please marks it best if it helps.

Thanks!