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
Shravan Kumar 71Shravan Kumar 71 

Breaking out of Loop Iteration

Hello Folks,

Below is the sample code :
Map<Id, Lead> ledMap = //Consider this will give me 3 records
for(Lead l : leadMap.values()){
if(l.status = 'New'){
//logic here
}
else if(l.status = 'Dead'){
//logic here
}
}

What I am looking at here is, if any record meet the first creteria (l.status = 'New') then I don't want to iterate the remaining records (in this case remaining 2 records). And in case if none of the records meet the first creteria (l.status = 'New') then only I need to perform the logic inside the else if condition. 

Looking forward for your inputs.

Thanks,
Shravan
 
Shaik Naga janiShaik Naga jani

Hi Shravan,
Use Boolean variable make true when the condition meets, that's it.
Check below code modify as per your requirement.
Sample Code
public Boolean bStatus = false;
 for(Lead leadIterator : lstLeads) {
     if(!bStatus && leadIterator.status = 'New'){
          //logic here
          bStatus = true;
      }
      else if(!bStatus && leadIterator.status = 'Dead'){
         //logic here
          bStatus = true;
      }
 }
Kindly mark this as solved if the reply was helpful.
Thanks
Shaik
 
Srikanth R 13Srikanth R 13
Hi Shravan,
 
 You can try using while loop and have this condition.

  boolean flag=true;
Integer i=0;
While(flag) {
Lead l = leadMap.values().get(i);
if(l.status = 'New'){ flag=false; }
else if(l.status = 'Dead'){ //logic here
}
}


Let me know if this helps.

Regards,
SR
Shravan Kumar 71Shravan Kumar 71
Thanks a lot Shaik & Srikanth for quick response. Unfronately, both the above solution didn't meet what I was looking for. Let me reframe my question which should help.

The requirement is to update a field on Lead, in case if there are two leads with the same email (1 lead is activate & 1 lead is inactive), I want the field to update only on active lead. So in the above example, among the 3 leads one will be activated and the remaining 2 is inactive. As soon as the iteration finds an activate lead, it should not iterate the remaining 2 leads. The lead can be the first record in the iteration or second or third.
Shaik Naga janiShaik Naga jani
Hi Shravan,
if you don't want iterate the loop when if any condition meets in the loop, you just use the break statement in the loop.
update code as per your requirement
Example
Map<Id, Lead> ledMap = //Consider this will give me 3 records
for(Lead l : leadMap.values()){
if(l.status = 'New'){
//logic here
break;
}
else if(l.status = 'Dead'){
//logic here
break;
}
}
Kindly mark this as solved if the reply was helpful.
Thanks
Shaik