Apex-java-for-loop

提供:Dev Guides
移動先:案内検索

Apex-JavaのようなForループ

Apexには、従来のJavaのような for ループがあります。

構文

for (init_stmt; exit_condition; increment_stmt) { code_block }

流れ図

Apex For Loop

次の例を考慮して、従来の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);

実行手順

  • forループ*のこのタイプを実行すると、Apexランタイムエンジンは次の手順を実行します-
  • ループの init_stmt コンポーネントを実行します。 このステートメントでは、複数の変数を宣言および/または初期化できます。
  • exit_condition チェックを実行します。 trueの場合、ループは継続し、falseの場合、ループは終了します。
  • code_block を実行します。 コードブロックは、数字を印刷することです。
  • increment_stmt ステートメントを実行します。 それは毎回増加します。
  • ステップ2に戻ります。

別の例として、次のコードは1〜100の数字をデバッグログに出力します。 構文を示すために、追加の初期化変数jが含まれていることに注意してください。

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

検討事項

このタイプの for loop ステートメントを実行するときは、次の点を考慮してください。

 *繰り返し処理中にコレクションを変更することはできません。* 'ListOfInvoices' *のリストを繰り返し処理している場合、繰り返し処理中は同じリスト内の要素を変更できません。
* 繰り返しながら元のリストに要素を追加できますが、繰り返しながら要素を一時リストに保持してから、元のリストにそれらの要素を追加する必要があります。