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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x