Have you ever found yourself with a list of objects and all you really wanted from that list was a Set
of their Id
s? 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
SELECT
Id
FROM
Account
];
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
[/java]
Shout out to ca_peterson for initially pointing this out in a response to a question answered on the Salesforce StackExchange.