Newer Version Available
Custom Iterators
1while (count < 11) {
2 System.debug(count);
3 count++;
4 }Using the Iterator interface you can create a custom set of instructions for traversing a List through a loop. This is useful for data that exists in sources outside of Salesforce that you would normally define the scope of using a SELECT statement. Iterators can also be used if you have multiple SELECT statements.
Using Custom Iterators
To use custom iterators, you must create an Apex class that implements the Iterator interface.
| Name | Arguments | Returns | Description |
|---|---|---|---|
| hasNext | Boolean | Returns true if there is another item in the collection being traversed, false otherwise. | |
| next | Any type | Returns the next item in the collection. |
All methods in the Iterator interface must be declared as global or public.
1IterableString x = new IterableString('This is a really cool test.');
2
3 while(x.hasNext()){
4 system.debug(x.next());
5 }Using Custom Iterators with Iterable
If you do not want to use a custom iterator with a list, but instead want to create your own data structure, you can use the Iterable interface to generate the data structure.
| Name | Arguments | Returns | Description |
|---|---|---|---|
| iterator | Iterator class | Returns a reference to the iterator for this interface. |
The iterator method must be declared as global or public. It creates a reference to the iterator that you can then use to traverse the data structure.
1global class CustomIterable
2 implements Iterator<Account>{
3
4 List<Account> accs {get; set;}
5 Integer i {get; set;}
6
7 public CustomIterable(){
8 accs =
9 [SELECT Id, Name,
10 NumberOfEmployees
11 FROM Account
12 WHERE Name = 'false'];
13 i = 0;
14 }
15
16 global boolean hasNext(){
17 if(i >= accs.size()) {
18 return false;
19 } else {
20 return true;
21 }
22 }
23
24 global Account next(){
25 // 8 is an arbitrary
26 // constant in this example
27 // that represents the
28 // maximum size of the list.
29 if(i == 8){return null;}
30 i++;
31 return accs[i-1];
32 }
33}1global class foo implements iterable<Account>{
2 global Iterator<Account> Iterator(){
3 return new CustomIterable();
4 }
5}1global class batchClass implements Database.batchable<Account>{
2 global Iterable<Account> start(Database.batchableContext info){
3 return new foo();
4 }
5 global void execute(Database.batchableContext info, List<Account> scope){
6 List<Account> accsToUpdate = new List<Account>();
7 for(Account a : scope){
8 a.Name = 'true';
9 a.NumberOfEmployees = 69;
10 accsToUpdate.add(a);
11 }
12 update accsToUpdate;
13 }
14 global void finish(Database.batchableContext info){
15 }
16}