Iterable Batch Apex

Iterable Batch Apex

Let’s traverse through data!

The Database.Batchable interface contains three methods that must be implemented. Namely, the start, the execute and the finish.

The start method can return either a QueryLocator or something called Iterable. Just like the below code

public (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}

In this post, we are going to discuss the latter, which is Iterable.

Iterable<String> i = new List<String> { 'X', 'Y', 'Z' };

With this knowledge, we can quite easily implement a Batch Apex to iterate over a list like :


public with sharing class ExampleBatchApex implements Database.Batchable<String>


public Iterable<String> start(Database.BatchableContext BC){


   return new List<String> { ‘Hello’, ‘ World‘, ‘ !!‘ };

}



public void execute(Database.BatchableContext info, List<String> strList){
   
    //let’s do something with the string for fun


     String myStr = strList.size() >0 ? strList[0] : '' ; 


}


public void finish(Database.BatchableContext info) { }


}


// executing the batch apex
Id jobId = Database.executeBatch(new ExampleBatchApex());{        


Most importantly, we can use this Iterable to traverse over generic List<object>

Consider an instance where you need to pass the entire list of objects which consists of different types of data such as string, Integer, Decimal, etc…


So we could take the advantage of Iterable shown below:


public with sharing class ExampleBatch implements Database.Batchable<object>

public List<object> objList = new List<Object>();

public ExampleBatch(List<Object> objList){

   this.objList = objList;

}

public Iterable<object> start(Database.BatchableContext BC) {

return objList;

}

public void execute(Database.BatchableContext BC, List<object> scope){

List<Custom_object__c> customobjList = new List<Custom_Object__c>();

for(Object obj : scope){


   Map<Object,Object> objMap = (Map<Object,Object>) obj ;

      // Do something

}

     // DML operation

}

public void finish(Database.BatchableContext BC) {

}

}        

Thus, sometimes Iterable can be helpful and save time and effort.

To view or add a comment, sign in

More articles by Deep B

  • Embracing SOLID Principles in Apex: A Guide for Salesforce Developers

    Salesforce development often involves creating robust and scalable solutions to meet the dynamic needs of businesses…

    1 Comment
  • Efficient SOQL queries

    If you’re doing development in an org with a Large Data Volume then you must be careful with SOQL For best performance,…

  • Dive into : Database.Stateful

    We know that in Salesforce we have a powerful way to execute things in bulk using Batch Apex . But seldom we arrive in…

  • Notable Nuances in JavaScript- 01

    This short read highlights some features that may not be majorly used 1. Replace can accept a callback function The…

    2 Comments

Explore content categories