Custom Iterators in salesforce

Custom Iterators in salesforce

If you want to use custom iterator then you need to implement Iterator Interface in Apex class.

Iterator Interface has two methods – hasNext and next.

hasNext :-

  • hasNext with Boolean as return type
  • Returns true if there is another item in the collection being traversed, false otherwise.

next :-

  • next with any type as return type
  • Returns the next item in the collection.

All methods should be declared either global or public in Iterator Interface, Iterators are not currently supported in for loops but supported only in while loop.


global class CustomIterable implements Iterator<Contact>{

List<Contact> con {get; set;}
 Integer i {get; set;}

public CustomIterable(){
 con = [SELECT Id, lastname FROM Contact LIMIT 5];
 i = 0;

// This is Iterator interface hasNext() method, it will return true if the list 'con' contains record else it will return false.

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

//This is Iterator interface next() method, it will keep on returning next element on the list until integer i reaches 5 and number 5 in if loop is the size of the list returned by soql query in above code.

global Contact next(){

if(i == 5){return null;}
 return con[i-1];

Be the first to comment

Leave a Reply

Your email address will not be published.