Custom Iterators

An iterator traverses through every item in a collection. For example, in a procedural loop, you define a condition for exiting the loop, and you must provide some means of traversing the collection, that is, an iterator. In this example, count is incremented by 1 every time the loop is executed.

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. The iterator 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.

The Iterator interface has the following instance methods:

NameArgumentsReturnsDescription
hasNext BooleanReturns true if there’s another item in the collection being traversed, false otherwise.
next Any typeReturns the next item in the collection.

All methods in the Iterator interface must be declared as global or public.

This example code uses a custom iterator to iterate through a list of strings.

1IterableString x = new IterableString('This is a really cool test.');
2
3while(x.hasNext()){
4   system.debug(x.next());
5}

Using Custom Iterators with Iterable 

If you don’t 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.

The Iterable interface has the following method:

NameArgumentsReturnsDescription
iterator Iterator classReturns 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.

In the following example a custom iterator iterates through a collection:

1public with sharing 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 with sharing class CustomIterable implements Iterable<Account> {
2   public Iterator<Account> iterator(){
3      List<Account> accounts =
4      [SELECT Id, Name,
5       NumberOfEmployees
6       FROM Account
7       WITH USER_MODE
8       LIMIT 10];
9      return new CustomIterator(accounts);
10   }
11}

The following is a batch job that uses an iterator:

1public with sharing 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 as user accsToUpdate;
13   }
14   public void finish(Database.BatchableContext info){
15   }
16}