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:

[java]
List accounts = [
SELECT
Id
FROM
Account
];

Set accountIds = new Set();
for(Account acc:accounts){
accountIds.add(acc.Id);
}
[/java]

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.

[java]
Set accountIds = new Map([SELECT Id FROM Account]).keySet();
[/java]

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

Advertisement

Go to Smartblog Theme Options -> Ad Management to enter your ad code (300x250)

Comments are closed.