Maps vs For loops, Round 1


In this example I want to use a technique that will help us to avoid inserting for loops inside other for loops. Let’s say you want to compare a couple of fields from different objects, in many situations you will find something similar to this:

//SOQL queries to retrieve our values

List<Lead> leadList = [SELECT Id, Email FROM Lead WHERE Email!= null]; 
List<Contact> contactList = [SELECT Id, Email FROM Contact WHERE Email != null]; 


for(Lead l: leadList)
{
    for(Contact c: contactList)
    {
        if(l.Email == c.Email)
        {
            system.debug('There are emails matching: '
                         + 'Contact Email:' + c.Email 
                           + ' with Lead Email: ' + l.email); 
        }
    }
}

If you run this code in an anonymous window it will run fine. The problem is that running for loops within for loops can easily reach the governor limits for the number of executed code statements which today is 200000.

In these situations is where we can use Map collections to help us reduce the possibility of reaching those nasty but important governor limits.

//SOQL queries to retrive our values

List<Lead> leadList = [SELECT Id, Email FROM Lead WHERE Email!= null]; 
List<Contact> contactList = [SELECT Id, Email FROM Contact WHERE Email != null]; 

//This map will contain one of the objects and we will be using later to compare. 
//Either Object can be used for this reference map. 

Map<String, Lead> leadMap = new Map<String, Lead>();

 for (Lead le : leadList)
 { 
   leadMap.put(le.Email, le);
 } 

//After passing key and value to our map(le.Email, le) we can use a for loop
//to compare both records. 

 for (Contact co: contactList)
 { 
 if (leadMap.containsKey(co.Email))
   { 
    system.debug('We found an equal email on a Lead for this Contact: ' + co.Email);
    } 

} 

This technique can save us of trouble and it is a good way to use Maps just to stay away from governor limits.

Leave a Reply

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