Given a Set of String, the task is to convert the Set to a comma separated String in Java.
Examples:
Input: Set<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"]
Output: "Geeks, For, Geeks"
Input: Set<String> = ["G", "e", "e", "k", "s"]
Output: "G, e, e, k, s"
Approach: This can be achieved with the help of join() method of String as follows.
- Get the Set of String.
- Form a comma separated String from the Set of String using join() method by passing comma ‘, ‘ and the set as parameters.
- Print the String.
Below is the implementation of the above approach:
import java.util.*;
public class GFG {
public static void main(String args[])
{
Set<String>
set = new HashSet<>(
Arrays
.asList( "Geeks" ,
"ForGeeks" ,
"GeeksForGeeks" ));
System.out.println( "Set of String: " + set);
String string = String.join( ", " , set);
System.out.println( "Comma separated String: "
+ string);
}
}
|
Output:
Set of String: [ForGeeks, Geeks, GeeksForGeeks]
Comma separated String: ForGeeks, Geeks, GeeksForGeeks