Welcome to SFDC Share Point

Salesforce Blogs

Efficiently generate Set<Id> from List<SObject>

Let’s check with some examples,

  1. Using Map

List<sobject> results = Database.query('Select Id From Account Limit 5');
Set<Id> accIds = (new Map<Id,Sobject>(results)).keyset();

In second line we are creating new Map<Id,Sobject> from the results of first line, and then taking the keys from this map. Once this done, heap space is released for this map, and so it is one of the efficient method.

  1. One Liner (Without Dynamic SOQL)

Set<Id> accIds = (new Map<Id,Account>([Select Id from Account Limit 5])).keyset();
  1. One Liner (With Dynamic SOQL)

String sQuery = 'Select Id from Account Limit 5';
Set<Id> accIds = (new Map<Id,Account>((List<Account>)Database.Query(sQuery))).keySet();

  • Facebook
  • Twitter

Site developed by Tejas Kapasi © 2021