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>
onSet<T>
., which when implemented would eliminate the need for the below workarounds.Example on
Set<String>
Debug:
Option 1 - cast it to
Iterable<T>
Result:
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
Result: