Generate a Set of Ids from a List of Objects

Have you ever found yourself with a list of objects and all you really wanted from that list was a Set of their Ids? Maybe you were planning on performing a SOQL query using those Ids in the WHERE clause or maybe you just needed the Ids to check a Map? I am guessing your initial reaction was to do something like:

List<Account> accounts = [
	SELECT 
		Id 
	FROM 
		Account
];

Set<Id> accountIds = new Set<Id>();
for(Account acc:accounts){
	accountIds.add(acc.Id);
}		

While this works, it is not the most efficient way of generating a Set of Ids. By utilizing a special Map constructor and the .keySet() method, you can generate your set of Ids in a single statement.

Set<Id> accountIds = new Map<Id, Account>([SELECT Id FROM Account]).keySet();

Shout out to ca_peterson for initially pointing this out in a response to a question answered on the Salesforce StackExchange.

7 Responses to “Generate a Set of Ids from a List of Objects”

  1. Peter Knolle
    August 16, 2013 at 7:53 am #

    This is really cool. Very script efficient!

    • August 16, 2013 at 11:24 am #

      As much as we joke about that, it actually does save a decent amount of script statements from being run. If you have a large amount of objects in your list, this can help increase performance a decent amount.

  2. Murtaza
    September 15, 2013 at 1:58 pm #

    Cool

    • September 15, 2013 at 2:55 pm #

      It is a pretty useful little bit of info to know. Saved quite of few statements for me on several occasions.

  3. Phani
    September 16, 2013 at 7:55 am #

    Great One!!! Helpful most of the times

  4. Julia
    May 11, 2017 at 6:01 am #

    I guide the students that how they can pass the exams and how can they get the certification for the latest knowledge this certification exam students click at exam http://www.myexamcollection.com/SY0-401-vce-questions.htm certification its better for your bright future and will helpful to attain the IT certification 

Leave a Comment