function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
srikanth cheera 11srikanth cheera 11 

what is the advantage of writing soql using map

Amit Chaudhary 8Amit Chaudhary 8
Gets Maps from SOQL Query 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.
 
//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.
//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);



Please check below post. I hope that will help you
1) http://amitsalesforce.blogspot.com/2016/09/collection-in-salesforce-example-using.html

Let us know if this will help you