Convert a List of String to a comma separated String in Java
Given a List of String, the task is to convert the List to a comma separated String in Java.
Examples:
Input: List<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"]
Output: "Geeks, For, Geeks"
Input: List<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 List of String.
- Form a comma separated String from the List of String using join() method by passing comma ‘, ‘ and the list as parameters.
- Print the String.
Below is the implementation of the above approach:
Program:
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
List<String>
list = new ArrayList<>(
Arrays
.asList( "Geeks" ,
"ForGeeks" ,
"GeeksForGeeks" ));
System.out.println( "List of String: " + list);
String string = String.join( "," , list);
System.out.println( "Comma separated String: "
+ string);
}
}
|
Output
List of String: [Geeks, ForGeeks, GeeksForGeeks]
Comma separated String: Geeks,ForGeeks,GeeksForGeeks
Last Updated :
21 Oct, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...