In Java, a List<String> can be efficiently converted into a comma-separated String using built-in utilities like String.join(), which concatenates list elements with a specified delimiter while ensuring clean, readable, and loop-free code.
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"
Syntax
String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
- delimiter: The string used to separate elements (, in this case)
- elements: The list of strings to be joined
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 result = String.join(",", list);
System.out.println("Comma separated String: " + result);
}
}
Output
List of String: [Geeks, ForGeeks, GeeksForGeeks] Comma separated String: Geeks,ForGeeks,GeeksForGeeks
Explanation:
- String.join() combines all list elements into one string.
- A comma (",") is inserted automatically between elements.
- This approach avoids loops and makes the code clean and readable.
- Time Complexity: O(N), where N is the number of elements in the list
- Auxiliary Space: O(1) (excluding the output string)