How to use custom iterator

An iterator traverses through every item in a collection. For example, in a while loop in Apex, you define a condition for exiting the loop, and you must provide some means of traversing the collection, that is, an iterator.

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

global class CustomIterable 
   implements Iterator<Account>{ 

   List<Account> accs {get; set;} 
   Integer i {get; set;} 

   public CustomIterable(){ 
       accs = 
       [SELECT Id, Name, 
       NumberOfEmployees 
       FROM Account 
       WHERE Name = 'false']; 
       i = 0; 
   }   

   global boolean hasNext(){ 
       if(i >= accs.size()) {
           return false; 
       } else {
           return true; 
       }
   }    

   global Account next(){ 
       if(i == 8){return null;} 
       i++; 
       return accs[i-1]; 
   } 
}

The following calls the above code:

global class example implements iterable<Account>{
   global Iterator<Account> Iterator(){
      return new CustomIterable();
   }
}

The following is a batch job that uses an iterator:

global class batchClass implements Database.batchable<Account>{ 
   global Iterable<Account> start(Database.batchableContext info){ 
       return new example(); 
   }     
   global void execute(Database.batchableContext info, List<Account> scope){ 
       List<Account> accsToUpdate = new List<Account>(); 
       for(Account a : scope){ 
           a.Name = 'true'; 
           a.NumberOfEmployees = 69; 
           accsToUpdate.add(a); 
       } 
       update accsToUpdate; 
   }     
   global void finish(Database.batchableContext info){     
   } 
}

Published by

Suhas Rathod

I'm Suhas Rathod. I am an energetic, self-confident and experienced Full Stack Programmer with a passion for working with different technology.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.