Category Archives: Salesforce

How to add a list of records to a map in Salesforce?

Normally we used to do something like this:

Map<Id,Contact> mapContact =  new Map<Id,Contact>();
public static void addListToMap(List<Contact> conList){
	for(Contact con:conList){
		mapContact.put(con.id,con);
	}
}

Here the processing time will be more(CPU execution time will be more), because we are iterating over a for loop to construct a map.

The best way to construct the map where we can avoid iteration like this:

public static void addListToMap(List<Contact> conList){
	Map<Id,Contact> mapContact =  new Map<Id,Contact>(conList);
}

Here the processing time will be very less.

Salesforce Stateful Batch Apex

Batch Apex is stateless by default. That means for each execution of your execute method, you receive a fresh copy of your object. All fields of the class are initialized, static and instance. If your batch process needs information that is shared across transactions, one approach is to make the Batch Apex class itself
stateful by implementing the Database.Stateful interface. Here is an example of stateful batch apex. In below example I want to count the “Customer – Direct” account records processed by the batch class.

Batch Apex:

global class AccountBatchApex implements Database.Batchable<sObject>, Database.Stateful{
    
    global integer numberofDirectCustomers = 0;
    
    global Database.QueryLocator start(Database.BatchableContext bc){
        String soqlQuery = 'SELECT Name, AccountNumber, Type From Account';
        return Database.getQueryLocator(soqlQuery);
    }
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
        
        for (Account acc : scope){
            if(acc.Type.equals('Customer - Direct')){
                numberofDirectCustomers++;
            }
        }
    }
    
    global void finish(Database.BatchableContext bc){
        
    }
}