[SalesForce] Which one is better “iterator” or “for-each loop”

Ierator and for-each loop both we use for traverse no of items, I have used for-each many times but I am not clear about iterator, means when we should use ierator. I am studying salesforce workbook example..

global class CustomIterable implements iterator<Account>{

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

  public CustomIterable(){
     accs =[SELECT Name fROM Account limit 5];
     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];
    }
}

//————

@isTest(seealldata=true)
global class IteratorClass{
    public static testmethod void main(){

        IteratorClass obj = new IteratorClass();
        Iterator<Account> acs =  obj.Iterator();
        system.debug(acs);

    }
    global Iterator<Account> Iterator(){

           return new CustomIterable();     
    } 
}

Best Answer

An iterator is useful where you don't want to do all the work (or occupy all the memory) up front and can divide the work of returning values up. So for example the iterator could fetch 10 of a total of 100 objects at once and hand each one back and then fetch the next 10 and so on.

The example you provide is fairly pointless and could be coded better.

An iterator can be used in a for loop but it's less clear and more code:

for (Iterator<Account> iter = new CustomIterable(); iter.hasNext(); ) {
    Account a = iter.next();
    System.debug('iter=' + a)
}

than the normal for-each loop:

for (Account a : [SELECT Name fROM Account limit 5]) {
    System.debug('list=' + a);
}

Note that Apex does not support this convenience pattern:

for (Account a : new CustomIterable()) {
    System.debug('list=' + a);
}

So an "iterator" and a "for each" are different things, not better or worse than each other.

One place where occasionally you may need to write your own Iterable is as a return value from Batchable.start. But don't use that if SOQL queries are involved as the normal 50,000 record governor limit applies whereas the start method that returns Database.QueryLocator can query up to 50 million records.

Related Topic