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
Afzaal HassanAfzaal Hassan 

APEX CPU LIMIT how do I use Maps ?

I have created a flow that based on some requirements, finds a list of accounts. The flow then passes this list of accounts and a new account owner (id) to an apex class. The apex class then updates all the accounts with this new owner and also updates each opportunity and each task listed under each activity with the same account owner. This was working fine till I stated updated large number of accounts. I am now hitting APEX CPU Limit. My apex class is shown below. I think I need to use Maps, but I dont know how to. Any ideas on how to rewrite this code to make it more efficient so that I dont run into APEX CPU limits? Thank you

public class LCD_AccountinCounty { @InvocableMethod(label='Account Owner Update flow' Description='Update Account Object with new owner')
public static void updateAccountOwner(List<FlowDetail> flowdetails) { List<Account> accList = new List<Account>();
for(FlowDetail fd : flowdetails){
for(Account acct : fd.accounts){
acct.OwnerId = fd.newAccountOwnerName;
acc.Salesperson__c = SalespersonName;
accList.add(acct);
}
}
update accList;
List<Opportunity> opportunities = new List<Opportunity>(); for(Opportunity opp: [SELECT Id, OwnerId, AccountId, Account.OwnerId FROM Opportunity WHERE AccountId IN :accList and StageName !='Closed']){
opp.OwnerId = opp.Account.OwnerId;
opportunities.add(opp);
}
update opportunities;
List<Task> activities = new List<Task>();
for(Task t: [SELECT Id, OwnerId, WhatId, Account.OwnerId FROM Task WHERE WhatId IN :accList]){
t.OwnerId = t.Account.OwnerId; activities.add(t);
}
update activities;
}
public with sharing class FlowDetail{
@InvocableVariable
public List<Account> accounts;
@InvocableVariable
public String newAccountOwnerName;
@InvocableVariable
public String SalespersonName;
}
}