top of page

Custom Iterator to traverse through collections

An iterator traverses through every item in a collection.

Use case - where we need some complex logic to build scope of the batch or for data that exists in sources outside of Salesforce.


Steps to implement Custom Iterator:

create an Apex class that implements the Iterator interface.

Note:

Iterators are not currently supported in for loops.

Implement the following methods of the Iterators - hasNext() and next().

In the constructor define the the scope of the batch.

global class CustomIterable

implements Iterator<Account>{


List<Account> accs {get; set;}

Integer i {get; set;}


public CustomIterable(){

accs =

[SELECT Id, Name,

NumberOfEmployees

FROM Account ];

i = 0;

}


global boolean hasNext(){

if(i >= accs.size()) {

System.debug('size of records ' + accs.size());

return false;

} else {

return true;

}

}


global Account next(){


if(accs[i] == null){

return null;

}

i++;

return accs[i-1];

}

}

The following class(that implements Iterable and implements its method Iterator) calls the above code:

global class example implements iterable<Account>{

global Iterator<Account> Iterator(){

return new CustomIterable();

}

}

To call the methods on the class example:

example obj = new example();

Iterator<Account> c = obj.Iterator();

while(c.hasNext()){

System.debug(c.next());

}


To use the Iterator in an Apex batch:

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){

}

}

Execute the batch:

batchClass myBatchObject = new batchClass();

Id batchId = Database.executeBatch(myBatchObject);


Recent Posts

See All

Comments


Post: Blog2_Post

©2020 by SalesforceDemystified. Proudly created with Wix.com

bottom of page