You need to create a list of identifiers of records from a query, but want to save on governor limits and not iterate over the list.
While writing Apex code, it's useful to understand how to reduce the number of executed code statements so that you can stay within the governor limits. This recipe shows a best practice you can apply when you need a list of identifiers of records, generated from a query.
If you want to create a list of IDs from a query to process later, you may write something like this:
//Fetching all accounts
List<account> accObj = [select Id from account limit 50000] ;
//Creating set of all account Ids
List<id> accIds = new List<id>() ;
//Fetching Account ids
for(Account acc : accObj)
Now if the query returns 50,000 records, this code will execute more than 50,000 code statements.
To avoid this you can simply initialize an Apex map with the query, and use it instead of creating a List. Here it is in action:
//Fetching all account in map
Map<id,account> aMap = new Map<id,account>([Select Id,Name from Account limit 50000]);
//Creating list of accounts
List<account> accList = aMap.values() ;
//Creating set of ids
Set<id> accIds = aMap.keySet() ;
This code uses only 3 script statements instead of 50,000.
Note that if the query returns sObject as a return type, then you can still use this approach by typecasting the result:
//Your dynamic query
String accountDynamicQuery = 'select id from account limit 50000' ;
//Typecasting it to map
Map<id,account> mapAcc = new Map<id,account>((List<account>)Database.query(accountDynamicQuery));