Convert a Set Id to Set String in Apex

Author: Bruce Tollefson Published: January 13, 2022; Modified: May 9, 2022
code

In apex, the Id is a primitive data type that maintains the data integrity of the data type by only allowing only Ids(or Strings with Id patterns). If you would like to test it out, put the following into anonymous apex and execute:

Id errorId = '001aaaaaaaaaaaa';

You receive an error with the following StringException: Invalid id: 001aaaaaaaaaaaa.

To keep the integrity there are times you would want to use the Id data type instead of a string data type. However if a method you are looking to use requires a string the Id will need to be turned into a string. This can be done quickly enough through casting the String. Ex:

Id castId = '005000000000001'; String castIdStr = (String)castId;

Set<Id> to Set<String>

However, if you have a Set<Id> while a method requires a Set<Id>, when trying to cast a List<Id> to a List<String> such as:

Set<Id> idSet = new Set<Id>{'005000000000001', '005000000000002'}; Set<String> strSet = (Set<String>)idSet;

You receive the following error: Incompatible types since an instance of Set<Id> is never an instance of Set<String>.

In order to remove that error and convert the set the JSON serialize and deserialize can be used in a small method:

public static Set<String> convertSetIdToListString(Set<Id> setID){ return (Set<String>)JSON.deserialize(JSON.serialize(setID), Set<String>.class); }

Set<Id> to List<String>

Likewise, if you need to convert a Set<Id> to a List<Id> and you try to cast the set:

Set<Id> idSet = new Set<Id>{'005000000000001', '005000000000002'}; List<String> strList = (List<String>)idSet;

The following error will arise: Incompatible types since an instance of Set<Id> is never an instance of List<String>.

This can be resolved with the following:

public static List<String> convertSetIdToListString(Set<Id> setID){ return (List<String>)JSON.deserialize(JSON.serialize(setID), List<String>.class); }

List<Id> to List<String>

When trying to cast a List<Id> to a List<String> no error is received:

List<Id> idList = new List<Id>{'005000000000001', '005000000000002'}; List<String> strList = (List<String>)idList;

GIT repo

Leave a Reply

Your email address will not be published. Required fields are marked *