Converting collections in apex

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> stringList= new List<String>{'abc','def'};

Set<String> setStrings = new Set<String>(stringList);

Permanent link to this article: https://salesforcebuddy.com/2021/04/converting-collections-in-apex/

Leave a Reply

Your email address will not be published.