Apex - For Loop simile a Java

C'è un tradizionale tipo Java for loop disponibile in Apex.

Sintassi

for (init_stmt; exit_condition; increment_stmt) { code_block }

Diagramma di flusso

Esempio

Considera il seguente esempio per comprendere l'uso del tradizionale ciclo for -

// 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);

Fasi di esecuzione

Quando si esegue questo tipo di file for loop, il motore di runtime Apex esegue i seguenti passaggi:

  • Esegui il file init_stmtcomponente del ciclo. Notare che più variabili possono essere dichiarate e / o inizializzate in questa istruzione.

  • Eseguire il exit_conditiondai un'occhiata. Se vero, il ciclo continua e se falso, il ciclo termina.

  • Esegui il file code_block. Il nostro blocco di codice serve per stampare i numeri.

  • Esegui il file increment_stmtdichiarazione. Aumenterà ogni volta.

  • Torna al passaggio 2.

Come altro esempio, il codice seguente restituisce i numeri da 1 a 100 nel registro di debug. Si noti che un'ulteriore variabile di inizializzazione, j, è inclusa per dimostrare la sintassi:

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

Considerazioni

Considera i seguenti punti durante l'esecuzione di questo tipo di for loop dichiarazione.

  • Non è possibile modificare la raccolta durante l'iterazione su di essa. Supponiamo che tu stia iterando sulla lista a'ListOfInvoices', quindi durante l'iterazione non è possibile modificare gli elementi nello stesso elenco.

  • È possibile aggiungere elementi nell'elenco originale durante l'iterazione, ma è necessario mantenere gli elementi nell'elenco temporaneo durante l'iterazione e quindi aggiungere quegli elementi all'elenco originale.