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.
1swfobject.registerObject("clippy.codeblock-2", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17global class CustomIterable
18 implements Iterator<Account>{
19
20 List<Account> accs {get; set;}
21 Integer i {get; set;}
22
23 public CustomIterable(){
24 accs =
25 [SELECT Id, Name,
26 NumberOfEmployees
27 FROM Account
28 WHERE Name = 'false'];
29 i = 0;
30 }
31
32 global boolean hasNext(){
33 if(i >= accs.size()) {
34 return false;
35 } else {
36 return true;
37 }
38 }
39
40 global Account next(){
41 // 8 is an arbitrary
42 // constant in this example
43 // that represents the
44 // maximum size of the list.
45 if(i == 8){return null;}
46 i++;
47 return accs[i-1];
48 }
49}1swfobject.registerObject("clippy.codeblock-3", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17global class foo implements iterable<Account>{
18 global Iterator<Account> Iterator(){
19 return new CustomIterable();
20 }
21}
221swfobject.registerObject("clippy.codeblock-4", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17global class batchClass implements Database.batchable<Account>{
18 global Iterable<Account> start(Database.batchableContext info){
19 return new foo();
20 }
21 global void execute(Database.batchableContext info, List<Account> scope){
22 List<Account> accsToUpdate = new List<Account>();
23 for(Account a : scope){
24 a.Name = 'true';
25 a.NumberOfEmployees = 69;
26 accsToUpdate.add(a);
27 }
28 update accsToUpdate;
29 }
30 global void finish(Database.batchableContext info){
31 }
32}