Think. Build. Salesforce Solutions.

Salesforce Consulting Services across Salesforce Clouds & Across App Lifecycles


Salesforce Developers Guide to Defining and Creating a map with id,records using Apex

By |2020-06-25T06:33:54+00:00January 12th, 2015|

In this blog, I will be explaining how to build a map of list dynamically through a loop which is commonly used in Apex programming ( development). For example
Map<id,<list<Contact>> accIdContactsmap = new Map<id,<list<Contact>>();
Before getting into the details, let’s reviews the definitions of Map and List.

Map: A map is a collection of key-value pairs, where the key part is always unique and value could be any data type like a List of objects, string, set, integer, or a map inside the map.

For example:

Map <String,Integer> strIntmap = new Map<String,Integer> ();
In the above example String is the key part and Integer is the value part of the map. Where String part will be always unique.

List: A list is an order collection of the same kind of elements and it can be accessed by their indices and it can hold any kind of data type like integer, String, etc

For example:
List<String> strList = new List<String>();
This is the list of String which can hold only string values.
So let’s create a map of list dynamically.
Map<id,<list<Contact>> accIdContactsmap = new Map<id,<list<Contact>>();

There are multiple approaches to create this kind of map. Here I will discuss the one that I find the easiest.
Suppose we have a list of contacts which hold the ids of its accounts and contact first names and last names as shown in the code below.
List<Contact> conlist = [SELECT accountid, id , firstname , lastname from Contact  WHERE accountid != null LIMIT 10];

Now if our requirement is to create a map which holds the account id as the key and related contact list as values, the following code snippet will achieve  the requirement.
Map<id,list<Contact>> accIdContactsmap = new Map<id,list<Contact>>();
List<Contact> conlist = [SELECT accountid, id , firstname , lastname from Contact  WHERE accountid != null LIMIT 10];

For(Contact con : conlist){
// Check if Contact’s account id not in Map
// If not in map then add key and create an instance of list of contacts as value.
accIdContactsmap.put(con.accountid, new list<Contact>());
/* add contact in a list on the basis of key value. get method of map will return the list of contacts related to account id  and add method of list will //add one contact to the list */
So here we have created the map of lists.
There is a small twist in line accIdContactsmap.get(con.accountid).add(con). If we expend this line into two parts code will be like this:
List<Contact> tempContactList  = accIdContactsmap.get(con.accountid);
tempContactList .add(con);

Leave A Comment