カスタムイテレーター
イテレーターは、コレクション内のすべての項目を辿ります。たとえば、Apex の while ループで、ループを終了する条件を定義し、コレクションを辿るいくつかの方法、つまりイテレーターを提供する必要があります。次の例では、ループが実行されるごとに count が 1 ずつ増加します。
1while (count < 11) {
2 System.debug(count);
3 count++;
4 }Iterator インターフェースを使用して、ループ全体のリストを辿るためのカスタムの一連の指示を作成できます。イテレーターは、通常 SELECT ステートメントを使用して範囲を定義する Salesforce 外の提供元にあるデータに役立ちます。複数の SELECT ステートメントがある場合にもイテレーターを使用できます。
カスタムイテレーターの使用
カスタムイテレーターを使用するには、Iterator インターフェースを実装する Apex クラスを作成する必要があります。
Iterator クラスには次のインスタンスメソッドがあります。
| 名前 | 引数 | 戻り値 | 説明 |
|---|---|---|---|
| hasNext | Boolean | コレクション内の��の項目が辿られている場合は true が返され、そうでない場合は false が返されます。 | |
| next | anyType | コレクション内の次の項目を返します。 |
Iterator インターフェース内のすべてのメソッドは global または public として宣言する必要があります。
カスタムイテレーターは while ループでのみ使用できます。次に例を示します。
イテレーターは現在、for ループではサポートされていません。
1IterableString x = new IterableString('This is a really cool test.');
2
3while(x.hasNext()){
4 system.debug(x.next());
5}Iterable とカスタムイテレーターの使用
リストでカスタムイテレーターを使用せずに独自のデータ構造を作成する場合、Iterable インターフェースを使用してデータ構造を生成できます。
Iterable インターフェースには次のメソッドがあります。
| 名前 | 引数 | 戻り値 | 説明 |
|---|---|---|---|
| iterator | Iterator クラス | このインターフェースのイテレーターへの参照を返します。 |
iterator メソッドは global または public として宣言する必要があります。データ構造の走査に使用できるイテレーターへの参照を作成します。
次の例では、コレクションのカスタムイテレーターの例を示します。
1public class CustomIterator
2 implements Iterator<Account>{
3
4 private List<Account> accounts;
5 private Integer currentIndex;
6
7 public CustomIterator(List<Account> accounts){
8 this.accounts = accounts;
9 this.currentIndex = 0;
10 }
11
12 public Boolean hasNext(){
13 return currentIndex < accounts.size();
14 }
15
16 public Account next(){
17 if(hasNext()) {
18 return accounts[currentIndex++];
19 } else {
20 throw new NoSuchElementException('Iterator has no more elements.');
21 }
22 }
23}1public class CustomIterable implements Iterable<Account> {
2 public Iterator<Account> iterator(){
3 List<Account> accounts =
4 [SELECT Id, Name,
5 NumberOfEmployees
6 FROM Account
7 LIMIT 10];
8 return new CustomIterator(accounts);
9 }
10}次は、イテレーターを使用する一括処理ジョブです。
1public class BatchClass implements Database.Batchable<Account>{
2 public Iterable<Account> start(Database.BatchableContext info){
3 return new CustomIterable();
4 }
5 public void execute(Database.BatchableContext info, List<Account> scope){
6 List<Account> accsToUpdate = new List<Account>();
7 for(Account acc : scope){
8 acc.Name = 'changed';
9 acc.NumberOfEmployees = 69;
10 accsToUpdate.add(acc);
11 }
12 update accsToUpdate;
13 }
14 public void finish(Database.BatchableContext info){
15 }
16}