[SalesForce] How to use Set with String.join(iterableObj, separator)

I was curious about using Set<ANY> in the String.join(iterableObj, separator) method. When I try this code:

Set<String> mySet = new Set<String>();
mySet.add('One');
mySet.add('Two');
mySet.add('Three');
System.debug('mySet= ' + mySet);

String mySet_Joined_Exception = String.join(mySet, ', ');
System.debug('mySet_Joined_Exception= ' + mySet_Joined);

It fails to compile pointing to the line String mySet_Joined_Exception = String.join(mySet, ', '); with the following error:

Method does not exist or incorrect signature: void join(Set,
String) from the type String

Which means that it's not possible to use directly Set<ANY> with the String.join() method. This happens because Set<ANY> does not implement Iterable interface, which clearly explained in another post "Do Apex collections implement iterable?".

Nevertheless, what are the workarounds to this issue?

Best Answer

There are quite a few options to solve this problem.

First, there is an idea Apex Code: Implement Iterable<T> on Set<T>., which when implemented would eliminate the need for the below workarounds.

Example on Set<String>

Set<String> mySet = new Set<String>();
mySet.add('One');
mySet.add('Two');
mySet.add('Three');
System.debug('mySet= ' + mySet);

Debug:

08:53:25.1 (2682641)|USER_DEBUG|[5]|DEBUG|mySet= {One, Three, Two}

Option 1 - cast it to Iterable<T>

String mySet_Joined = String.join((Iterable<String>)mySet, ', ');
System.debug('mySet_Joined= ' + mySet_Joined);

Result:

08:53:25.1 (2944980)|USER_DEBUG|[8]|DEBUG|mySet_Joined= One, Two, Three

UPDATE re- Option 1 - see this post for more info about why (Iterable<String>)mySet should not be used.

Option 2 - convert original Set into List

String mySet_Joined_List = String.join(new List<String>(mySet), ', ');
System.debug('mySet_Joined_List= ' + mySet_Joined_List);

Result:

08:57:13.1 (2812911)|USER_DEBUG|[11]|DEBUG|mySet_Joined_List= One, Two, Three
Related Topic