Convert a Set<Id> to Set<String> using Apex

Here's a clever (ugly) one-liner.

Set<Id> ids = new Set<Id>{'001C000001DgWjE','001C000001DgWjD'};

// Here's the one line!
Set<String> idStrs = (Set<String>)JSON.deserialize(JSON.serialize(ids), Set<String>.class);

System.debug('idStrings=' + idStrs);

You can explicitly cast from List<Id> to List<String> and vice-versa and use that to convert Sets between types by converting the Set to a List first and passing the List a new Set<>( List<> ) call.

Here's the simplest single-line method to convert from a Set of Ids to a Set of Strings, where idSet is defined as Set<Id> idSet:

Set<String> stringSet = new Set<String>( (List<String>)new List<Id>( idSet ) );

Here are some more examples of converting Sets and Arrays between Ids to String types:

// Convert List<Id> to List<String> - Id[] and String[] array notation works as well.
List<Id> ids = new List<Id>{ '001800000000001AAA', '001800000000002AAA' };
List<String> strings = new List<String>( (List<String>)ids );

// Convert Set<Id> to Set<String>
Set<Id> idSet = new Set<Id>{ '001800000000001AAA', '001800000000002AAA' };
Set<String> stringSet = new Set<String>( (List<String>)new List<Id>( idSet ) );

// Convert List<String> to List<Id>
List<String> stringList = new List<String>{ '001800000000001AAA', '001800000000002AAA' };
List<Id> idList = new List<Id>( (List<Id>)stringList );

// Convert Set<String> to Set<Id>
Set<String> stringSet2 = new Set<String>{ '001800000000001AAA', '001800000000002AAA' };
Set<Id> idSet2 = new Set<Id>( (List<Id>)new List<String>( stringSet2 ) );

I couldn't find a direct one line conversion but below is a way to convert a set of ids to a set of strings without using a for loop. I'm assuming you wanted a one liner but here you go anyway!

Set<Id> setIds = new Set<Id>();

List<Id> setIdList = new List<Id>();

setIdList.addAll(setIds);

String Ids = String.join(setIdList, ',');

Set<String> setIdSet = new Set<String>(Ids.split(','));