Get set of Ids from SObject List

Get set of Ids from your SObject list without iteration

Get set of Ids from your SObject list without iteration

You don’t need to iterate through the list of SObjects to get the set of their Ids:

Don't do this
Set<Id> leadsIds = new Set<Id>();

for (Lead l : leads) {
    leadsIds.add(l.Id);
}

You can simply cast your List to Map and then use keyset:

Do this
Set<Id> leadsIds = (new Map<Id, Lead>(leads)).keySet();

Get set of Ids from your SObject list without iteration

You can also do that directly on SOQL query result:

Do this
Set<Id> leadsIds = new Map<Id, Lead>([
    SELECT Id FROM Lead LIMIT 10
]).keySet();

Text and code were extracted from the original slide. Plain-text version of the whole catalog