How can I efficiently generate a Set from a List structure?

I have a bit of code where I’ve written a SOQL query that returns a list of SObject records, however I need a Set<Id> structure to pass to another method that I don’t have control of (and thus can’t change the method signature of).

How can I turn my returned List<SObject> into a Set<Id>? Is the best option just a for loop?


This trick only works on the Id field, but you can use the Map constructor that accepts an SObject list to do this without consuming a script statement for each element in the List.

For example:

List<SObject> results = Database.query(someSOQL);
Set<Id> resultIds = (new Map<Id,SObject>(results)).keySet();

What this second line does is create a new Map<Id,SObject> from the results list using a special constructor, and then take the map’s set of keys via the keySet() method. Then the map falls out of scope and it’s heap space is released, leaving you with a very governor-efficient set.

Source : Link , Question Author : ca_peterson , Answer Author : Bahman.A

Leave a Comment