Apex - Java-like For Loop


Advertisements

There is a traditional Java-like for loop available in Apex.

Syntax

for (init_stmt; exit_condition; increment_stmt) { code_block }

Flow Diagram

Apex For Loop

Example

Consider the following example to understand the usage of the traditional for loop −

// The same previous example using For Loop
// initializing the custom object records list to store the Invoice Records
List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();

PaidInvoiceNumberList = [SELECT Id,Name, APEX_Status__c FROM APEX_Invoice__c WHERE 
   CreatedDate = today];

// this is SOQL query which will fetch the invoice records which has been created today
List<string> InvoiceNumberList = new List<string>();

// List to store the Invoice Number of Paid invoices
for (Integer i = 0; i < paidinvoicenumberlist.size(); i++) {
   
   // this loop will iterate on the List PaidInvoiceNumberList and will process
   // each record. It will get the List Size and will iterate the loop for number of
   // times that size. For example, list size is 10.
   if (PaidInvoiceNumberList[i].APEX_Status__c == 'Paid') {
      
      // Condition to check the current record in context values
      System.debug('Value of Current Record on which Loop is iterating is 
         '+PaidInvoiceNumberList[i]);
      
      //current record on which loop is iterating
      InvoiceNumberList.add(PaidInvoiceNumberList[i].Name);
      // if Status value is paid then it will the invoice number into List of String
   }
}

System.debug('Value of InvoiceNumberList '+InvoiceNumberList);

Execution Steps

When executing this type of for loop, the Apex runtime engine performs the following steps −

  • Execute the init_stmt component of the loop. Note that multiple variables can be declared and/or initialized in this statement.

  • Perform the exit_condition check. If true, the loop continues and if false, the loop exits.

  • Execute the code_block. Our code block is to print the numbers.

  • Execute the increment_stmt statement. It will increment each time.

  • Return to Step 2.

As another example, the following code outputs the numbers 1 – 100 into the debug log. Note that an additional initialization variable, j, is included to demonstrate the syntax:

//this will print the numbers from 1 to 100}
for (Integer i = 0, j = 0; i < 100; i++) { System.debug(i+1) };

Considerations

Consider the following points while executing this type of for loop statement.

  • We cannot modify the collection while iterating over it. Suppose you are iterating over list a 'ListOfInvoices', then while iterating you cannot modify the elements in the same list.

  • You can add element in the original list while iterating, but you have to keep the elements in the temporary list while iterating and then add those elements to the original list.

apex_loops.htm
Advertisements