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
Koustubh MasurkarKoustubh Masurkar 

How can I use Map instead of inner for loop?

I wrote a trigger to count number of open cases for contacts. 
To reduce complexity and obey governor limits, how can I use Map instead of inner for loop in this case? 
 
trigger CountOpenCases on case (after insert, after update) {
  List<Case> caseList = trigger.new;
  set<Id> contactIdSet = new set<Id>();
  for(Case cs: caseList ){
     contactIdSet .add(cs.contactId);
  }
  if(contactIdSet.size() > 0){
    List<contact> lstcontact = [select id, (select id, status from Cases)from contact where id IN: contactIdSet ];
       if(lstcontact.size() > 0){
          for(contact acc: lstcontact)
          { 
             Integer openCases = 0;
             for(Case c : acc.cases){
                 if(c.Status != 'Closed')
                   openCases++;
             }
             acc.Open_Cases__c = openCases; 
          }
          update lstcontact;
       }
  }
}

 
Best Answer chosen by Koustubh Masurkar
Maharajan CMaharajan C
Hi Koustubh,

You can use the below changes to remove the inner for loop without Map:

trigger CountOpenCases on case (after insert, after update) {
  List<Case> caseList = trigger.new;
  set<Id> contactIdSet = new set<Id>();
  for(Case cs: caseList ){
     contactIdSet .add(cs.contactId);
  }
  if(contactIdSet.size() > 0){
    List<contact> lstcontact = [select id, (select id, status from Cases where status!= 'Closed')from contact where id IN: contactIdSet ];
       if(lstcontact.size() > 0){
          for(contact acc: lstcontact)
          { 
             acc.Open_Cases__c = acc.cases.size(); 
          }
          update lstcontact;
       }
  }
}

Thanks,
Maharajan.C