Apex Aide apexaide

Converting collections in apex

Salesforce Learning Buddy· ·Intermediate ·Developer ·1 min read
Summary

This content explains how to convert between different collection types in Apex, specifically between List and Set, and between Id and String types. It provides code examples demonstrating how to easily cast or create new collections from existing ones for common Salesforce development tasks. Knowing these patterns helps Salesforce developers handle data structure conversions cleanly, which is critical when working with Salesforce IDs and strings across triggers, classes, and integrations. After reviewing this, teams can better manage collection data transformations in Apex code.

Takeaways
  • Convert List<Id> to List<String> by casting or creating new List<String> from List<Id>.
  • Convert Set<Id> to Set<String> via intermediate List conversion.
  • Transform List<String> to List<Id> by casting similarly.
  • Switch between Set<String> and Set<Id> using List as an intermediary.
  • Convert between Set and List of the same data type using constructor methods.

List<Id> to List<String> // Convert List<Id> to List<String> List<Id> ids = new List<Id>{ '0011b00000v3UeD', '0011b00000wUJSs' }; List<String> strings = new List<String>( (List<String>)ids ); Set<Id> to Set<String> // Convert Set<Id> to Set<String> Set<Id> idSet = new Set<Id>{ '0011b00000v3UeD', '0011b00000wUJSs' }; Set<String> stringSet = new Set<String>( (List<String>)new List<Id>( idSet ) ); List<String> to List<Id> // Convert List<String> to List<Id> List<String> stringList = new List<String>{ '0011b00000v3UeD', '0011b00000wUJSs' }; List<Id> idList = new List<Id>( (List<Id>)stringList ); Set<String> to Set<Id> // Convert Set<String> to Set<Id> Set<String> stringSet2 = new Set<String>{ '0011b00000v3UeD', '0011b00000wUJSs' }; Set<Id> idSet2 = new Set<Id>( (List<Id>)new List<String>( stringSet2 ) ); Set to List of same data type Set<String> stringSet = new Set<String>{'abc','xyz'}; List<String> listStrings = new List<String>(stringSet); List to Set of same data type List<String> stri…

ApexSalesforce