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
SFDC New learnerSFDC New learner 

optimize the code

Hi All,

 I am trying to update the account upon lead update.
Need help to optimize my code. Just want to avoid multiple for loops.

public class LeadAfterUpdateHandler {
    
    public static void updateRelatedAccount(List<Lead> newLeads, Map<Id,Lead> LeadOldMap){
        List<Lead> ChangedLeads = new List<Lead>();
        Map<String,String> LeadAccFieldsMap = new Map<String,String>();
        List<Account> accList = new List<Account>();
        List<Lead_to_Account_Sync__c> csList = [Select Id,Account_Field_Name__c,Lead_field_Name__c from Lead_to_Account_Sync__c];
        for(Lead_to_Account_Sync__c cs : csList){
           
            LeadAccFieldsMap.put(cs.Lead_field_Name__c,cs.Account_Field_Name__c) ;  
            }
        }
        for(Lead l : newLeads){
            for(String cs1 : LeadAccFieldsMap.keySet()){
                if(l.get(cs1) != LeadOldMap.get(l.id).get(cs1)){
                    ChangedLeads.add(l);
                    break;
                }
            }
        }
        
        for(Lead l : ChangedLeads){
            Account a = new Account(Id = l.Account_Id__c);
            a.Name = (String)l.get('LastName');
            for(String cs1 : LeadAccFieldsMap.keySet()){
                
                a.put(LeadAccFieldsMap.get(cs1),(String)l.get(cs1));
                system.debug('for a :::' + a);
            }
            system.debug('a:::' + a);
            accList.add(a);
            
        }
        
        if(accList.size() > 0){
            update accList;
        }
    }

}
Thanks,
Sirisha
abhishek singh 497abhishek singh 497
Hello,
Can you please just mention your requirements what you are trying to achieve??

Thanks & Regards,
Abhishek Singh.
SFDC New learnerSFDC New learner
Hi,

I am trying to map lead with Account using a custom setting. When fields like Phone, picklist field or any datatype changes in the lead should get updated in Account.

Thanks,
Sirisha