There might be a business requirement which need a list of Ids from SOQL. Instead of getting the SOQL result saved in a List and then iterating over it to get the Ids, rather the best practice would be to assign the result to a Map and then get the key values. With the implementation of Map, the need for a loop can be avoided.

Below is the sample code to get list of Ids using List and For loop

List<Id> accIds = new List<Id>();
List<Account> accList = [SELECT Name From Account LIMIT 2];
System.debug('Account List ## ' + accList);
for(Account oAcc : accList){
System.debug('Account Ids ##'+ accIds);

Please follow the below lines of code to optimize the above lines and it’s clearly visible that the complexity of having a loop and another variable is omitted by using Map instead of List while storing the SOQL result.

Map<Id, Account> accMap = new Map<Id, Account>([SELECT Name FROM Account LIMIT 2]);
System.debug('Account Map ## ' + accMap);
System.debug(new List<Id>(accMap.keyset()));

The map key must be declared with an ID or String data type, and the map value must be declared as an sObject data type.

Leave a Comment

Your email address will not be published.