Efficiently Generate a Set from List

Efficiently Generate a Set from List

On May 9, 2025, Posted by , In Apex,Salesforce Technical Questions, With Comments Off on Efficiently Generate a Set from List
Efficiently Generate a Setid from Listid

Question:

I have a SOQL query that returns a List<SObject> structure, and I need to convert this into a Set<Id> to pass to another method. The method’s signature cannot be changed, so I must provide the data in the required format. What is the best way to achieve this conversion? Would a simple for loop suffice, or are there other options I should consider?

Answer:

Yes, a simple for loop can accomplish this. By iterating through the List<SObject>, you can extract the IDs and add them to a Set<Id>. This approach is both straightforward and efficient for typical use cases where the List<SObject> does not contain duplicates.

Boost your career with expert Salesforce training in Chandigarh—join our free demo and start your journey to certification today!!!

Here’s an example:

List<SObject> records = [SELECT Id FROM Account LIMIT 10];
Set<Id> recordIds = new Set<Id>();
for (SObject record : records) {
    recordIds.add(record.Id);
}

Code explanation:
The code performs a SOQL query to retrieve up to 10 Account records and stores them in a List<SObject>. It then iterates through the list, extracts the Id of each record, and adds it to a Set<Id>, ensuring a collection of unique IDs.

However, there are alternative methods that can be used depending on your requirements.

1.Using a Map to Avoid Duplicates:

If the source of the List<SObject> is not guaranteed to be unique (e.g., if the list was constructed manually or processed elsewhere), using a Map<Id, SObject> is a safer option. This avoids issues caused by duplicate IDs in the list, which can lead to runtime errors. Here’s an example:

List<SObject> records = new List<SObject>();
records.add([SELECT Id FROM Account LIMIT 1]); // Add a record
records.add(records[0]); // Add a duplicate

Map<Id, SObject> recordsMap = new Map<Id, SObject>();
recordsMap.putAll(records); // Handles duplicates internally
Set<Id> recordIds = recordsMap.keySet();

Code explanation:
The code demonstrates handling duplicates in a List<SObject> by using a Map<Id, SObject>. Adding the list to the map with putAll ensures only unique records are retained, as duplicate IDs are automatically overwritten, and the resulting Set<Id> is extracted using the map’s keySet() method.

2.Using SOQL Results Directly:

If you are working with SOQL query results directly, the Map<Id, SObject> constructor provides a compact solution. This works because SOQL guarantees unique IDs for query results:

List<SObject> records = [SELECT Id FROM Account LIMIT 10];
Set<Id> recordIds = new Map<Id, SObject>(records).keySet();

Code explanation:
The code performs a SOQL query to fetch 10 Account records and stores them in a List<SObject>. It then creates a Map<Id, SObject> using the list, automatically mapping each record’s Id as the key, and extracts the keys as a Set<Id> for further use.

3.Utility Method Example:

public static Set<Id> getRecordIds(List<SObject> records) {
    return new Map<Id, SObject>(records).keySet();
}

Code explanation:
The getRecordIds method converts a List<SObject> into a Set<Id> by leveraging the Map<Id, SObject> constructor, which automatically uses the IDs of the records as keys. This ensures any duplicate IDs are handled efficiently, and the resulting keySet() provides a unique collection of IDs.

Using the Map approach is robust but may be slower than a basic for loop due to additional overhead. For guaranteed unique SOQL results, all methods work seamlessly. If working with potentially non-unique lists, prefer the Map method for safety.

Salesforce Training in Chandigarh – Empower Your Future!

Transform your career with our top-tier  Salesforce training in Chandigarh, designed for both beginners and experienced professionals. Master Salesforce CRM with a hands-on approach, gain practical experience on real-time projects, and receive expert coaching to excel in certifications like Salesforce Admin and Developer. Our comprehensive curriculum ensures you’re fully equipped for the job market and ready to take your career to the next level.

Our training emphasizes practical, industry-oriented learning with a focus on real-world applications. With tailored guidance, extensive course materials, and thorough support for certification and interview preparation, we ensure you’re prepared for success.

Join us today for a free demo session and start your journey toward a rewarding Salesforce career!!!

Comments are closed.