Thursday, April 24, 2014

How to get Maps from SOQL Query in salesforce?

How to get Maps from SOQL Query in salesforce?

As we all know, Apex code has limitation of  Number of code statements that can be executed. While writing Apex code, we should take care of number of code statement that are  executed to avoid governor limits. It is useful to understand how to reduce the number of executed code statements so that we can stay within the governor limits.

Normally we get list of records in a SOQL query.Sometime we also need set of id’s or map of record id’s and record or list of record id’s.

Apes code for above requirement will be as below:



//Creating List of all account Ids
List<id> accIdsList = new List<id>() ;

//Creating set of all account Ids
Set<id> accIdsSet = new Set<id>() ;

//Creating Map with account id as key and account record as value
Map<Id,Account> accountIdObjMap = new Map<Id,Account>();

//Fetching all accounts
List<account> accList = [select Id,name,site,rating,AccountNumber from account limit 50000] ;

//Fetching Account ids
for(Account acc : accList){
    accIdsSet.add(acc.id);
    accIdsList.add(acc.id);
    accountIdObjMap.put(acc.id,acc);
}



In the code above, if there are large number of records(say 50000) then for loop will be executed 50000  times and also every line in for loop will be executed 50000 times. We can avoid this unnecessary for loop by using good SOQL query which will return map instead of list. After that we can easily get list of accounts or set of account Id’s or List of account Id’s using methods.

New Apex Code will be as below:


//Creating List of all account Ids
List<id> accIdsList = new List<id>() ;

//Creating set of all account Ids
Set<id> accIdsSet = new Set<id>() ;

//Fetching all accounts
List<account> accList = new List<Account>();

//Creating Map with account id as key and account record as value
Map<Id,Account> accountIdObjMap = new Map<Id,Account>([select Id,name,site,rating,AccountNumber from account limit 50000]);

//getting list of account using map.values method
accList = accountIdObjMap.values();

//getting set of account Id's using map.keySet method
accIdsSet = accountIdObjMap.keySet();

//getting list of account Id's using list.addAll method
accIdsList.addAll(accIdsSet);





1 comments:

nick jones said...


thanks for sharing..
Server and Storage

Post a Comment

 
| ,