I'm trying to compare dates of old contracts and new contracts (trigger.new) from the same account, the new contracts are imported and are from a lot of different accounts. But the performance of it has to be better. So I was thinking to do a map of old contracts that compare by the AccountId and not iterate all contracts every time. Below is my code so far. Is it possible to do it using a map, maybe like Map <Id, List<Contract>>
? And how I iterate over a map like this one?
public class NewContracts {
public static void comparingContracts(List<Contract> newContracts){
Set<String> setAccounts = new set<String>();
list<Contract> oldContracts = new list<Contract>();
for (Contract c: newContracts){
setAccounts.add(c.AccountId);
}
oldContracts = [SELECT AccountId, EndDate, RecordTypeId FROM Contract WHERE AccountId in :setAccounts];
for(Contract oCon: oldContracts){
for(Contract nCon: newContracts){
if (oCon.AccountId == nCon.AccountId ){
nCon.checkTest__c= compareDate(oCon.EndDate, nCon.StartDate);
}
}
}
}
}