1

Scenario

A New Lead is inserted, if it matches criteria, the lead ownerid is Updated based on an email field on the lead.

Problem

Write code that takes the email address and queries all Users for one which has an email matching the lead field.

Question

How do I optimize this Operation? I currently am doing it with 3 nested for loop. I would like to do this using a map< email,User> so I can take advantage of the loopups instead of raw iteration. This method is inside a trigger helper class. Newlead is a a map of newleads.

    Public static void updateOwnerIdForPartner() {
    List<lead> leadsToUpdate = new list<lead>();
    List<String> emails = new list<String>();


    for(Lead lead: newLead) {

        if(lead.Sales_Rep_Email__c != null && lead.recordtypeid == '012C0000000M000000' && lead.LeadSource == 'Partner') {
            leadsToUpdate.add(lead);
            emails.add(lead.Sales_Rep_Email__c);
        }
    }
    if(leadsToUpdate.size() > 0) {

        for(List<user> users: [SELECT Id, email FROM user WHERE email IN :emails]) {
            for(User user : Users) {
                for(Lead lead : leadsToUpdate) {
                    if(lead.Sales_Rep_Email__c == user.email) {
                        lead.OwnerId = user.id;
                    }
                }
            }
        }
    }

}
  • 1
    Don't use hard-coded Ids... Regardless, where are you getting newLeads or leadsToUpdate? You should avoid using static properties to track stateful data. – Adrian Larson Jan 14 '19 at 15:48
  • lead trigger fires helper method on before insert of lead. Trigger passes trigger.newmap to the helper class before hand. Which is what newleads is the recipient of. – Ryan Sherry Jan 14 '19 at 16:01
1

Creating the map is quite simple. It's like any other map, nothing special here.

Map<String, List<Lead>> emailToLeads = new Map<String, List<Lead>>();
for (Lead record : someCollection)
{
    if (!emailToLeads.containsKey(record.Email))
        emailToLeads.put(record.Email, new List<Lead>());
    emailToLeads.get(record.Email).add(record);
}

Note that since multiple records can have the same Email, you use List<Lead> as the map value, rather than a single record. Note also that this field is not unique on User either, so if multiple have the same Email, you will have arbitrarily assign one of them.

  • 4
    Map keys are case sensitive, will it be good to lowercase all email id and then set them as keys? – Pranay Jaiswal Jan 14 '19 at 16:20
  • Fair point. Yeah making them lower case would be a good idea. – Adrian Larson Jan 14 '19 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.