How to convert a List of String to a comma separated String in Java
In this section, we will show you how to convert a List of String to a comma separated String in Java.
1. List
1.1 Using String.join()
join (CharSequence delimiter, Iterable<? extends CharSequence> elements): This method is useful when we have to join iterable elements. Some of the common Iterables are – List, Set, Queue, and Stack.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.
asList("Java","Kotlin","Python","C");
String result = String.join(",", list);
System.out.println(result);
}
}
Console Output:
Java,Kotlin,Python,C
1.2 Stream Collectors.joining()
joining(CharSequence delimiter):We pass a delimiter to get back a Collector, which concatenates the elements separated by the specified delimiter.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.
asList("Java","Kotlin","Python","C");
String result = list.stream().
collect(Collectors.joining(","));
System.out.println(result);
}
}
Console Output:
Java,Kotlin,Python,C
2. Custom method to join the String
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.
asList("Java","Kotlin","Python","C");
String result = join(',',list);
System.out.println(result);
}
private static String join(char separator, List<String> input) {
if (input == null || input.size() <= 0)
{
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.size(); i++) {
sb.append(input.get(i));
if (i != input.size() - 1) {
sb.append(separator);
}
}
return sb.toString();
}
}
Console Output:
Java,Kotlin,Python,C