Populating a inner List in a Map collection


A simple way to populate a list that inside a map collection could be done like this.
You can run that piece of code in your developer console.

/**********************************************************************
*
*    Populating a List inside a Map collection
*
************************************************************************/

List<Account> acclist = [SELECT Id, Name,
                            (SELECT Id, lastName FROM Contacts) 
                                FROM Account LIMIT 50];

// This map will be contain the list of contacts as values and the 
// account ids as key. 
Map<Id,List<Contact>> accConMap = new Map<Id,List<Contact>>();
          
     for(account acc : acclist)
     {
      List<Contact> innerList = new List<Contact>();         
      for(contact c: acc.contacts)
        
        innerList.add(c);
        accConMap.put(acc.id, innerList); 
         
     }

// accConMap.put(acc.Id, innerList) will insert key and values to our map 
//

As you can see it is quite simple.
All you need to do is to iterate over the accounts an add all related contacts to a list.
This list will be added to our map together with the AccountId which will be the key in our map.

One Comment

  • Hari Prakash

    We can do even in simpler way like below .

    Map<Id,List> accConMap = new Map<Id,List>();
    for(account acc : acclist) {
    accConMap.put(acc.id, acc.contacts);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *