Java Like For Loop
在Apex中有傳統(tǒng)的類似于Java的for循環(huán)。
語法:
for (init_stmt; exit_condition; increment_stmt) { code_block }
流程圖:
示例:
我們的例子使用傳統(tǒng)的for循環(huán):
//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 the 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);
執(zhí)行步驟:
當(dāng)執(zhí)行這種類型的for循環(huán)時,Apex運(yùn)行時引擎按順序執(zhí)行以下步驟:
1、執(zhí)行循環(huán)的init_stmt組件。 注意,可以在此語句中聲明和/或初始化多個變量。
2、執(zhí)行exit_condition檢查。 如果為true,循環(huán)繼續(xù)。 如果為false,則循環(huán)退出。
3、執(zhí)行code_block。 我們的代碼塊是打印數(shù)字。
4、執(zhí)行increment_stmt語句。 它將每次增加。
5、返回步驟2。
作為另一個示例,以下代碼將數(shù)字1-100輸出到調(diào)試日志中。 注意,還包括一個附加的初始化變量j,語法:
//this will print the numbers from 1 to 100}
for (Integer i = 0, j = 0; i < 100; i++) { System.debug(i+1) };
注意事項(xiàng):
1、我們不能在迭代它時修改集合。 假設(shè)你正在遍歷列表“ListOfInvoices”,然后在迭代時不能修改同一列表中的元素。
2、您可以在迭代時在原始列表中添加元素,但是您必須在迭代時將元素保留在臨時列表中,然后將這些元素添加到原始列表。
更多建議: