Java – Convert List to comma-separated String
This tutorial shows several ways for converting a List to a comma-separated String in Java.
1- Java 7
The traditional way of converting a List to a comma-separated String in Java 7 and older versions is through using StringBuilder as the following:
1 2 3 4 5 6 7 8 9 | public static String convertUsingStringBuilder(List<String> names) { StringBuilder namesStr = new StringBuilder(); for(String name : names) { namesStr = namesStr.length() > 0 ? namesStr.append(",").append(name) : namesStr.append(name); } return namesStr.toString(); } |
2- Java 8
In Java 8, there are 2 conversion ways.
2.1. String.join()
The most common way is through using the join() method provided by the String object.
1 2 3 4 | public static String convertUsingJava8(List<String> names) { return String.join(",", names); } |
2.2. Collectors.joining()
The other less common way is through converting the List into a Stream and then collecting it as a comma-separated String.
1 2 3 4 | public static String convertUsingJava8(List<String> names) { return names.stream().collect(Collectors.joining(",")); } |
3- Apache Commons Lang
Apart from JDK, you can still convert a List to a comma-separated String using Apache Commons Lang library through its StringUtils utility class.
1 2 3 4 | public static String convertUsingApacheCommons(List<String> names) { return StringUtils.join(names, ','); } |