Java 8 How to Convert List to String comma separated values

By |2019-04-20T22:37:46+05:30April 20th, 2019|java8|

Here we will see how to convert List to String comma separated values using Java 8.

List to String Comma Separated:

Let’s take a simple java List<String>, filled with Strings of elements.

1. List to String using String.join():

List<String> countries = Arrays.asList("Java","Spring","Hibernate","Python","C");
String countrieswithComma = String.join(",",countries);
System.out.println(countrieswithComma);

Output:

Java,Spring,Hibernate,Python,C

2. List to String comma separate using Streams:

Java 8 streams are beneficial to collect data in different formats.

List<String> countries = Arrays.asList("Java","Spring","Hibernate","Python","C");
String countrieswithComma = countries.stream().collect(Collectors.joining(","));
System.out.println(countrieswithComma);

Output:

Java,Spring,Hibernate,Python,C

3. List to comma separate strings using Java 7:

If you are using legacy java version (before Java 8), you can even convert the list to string comma separate values by using the following logic.

List<String> countries = Arrays.asList("Java","Spring","Hibernate","Python","C");
StringBuffer buffer = new StringBuffer();
for (String country : countries){
     buffer.append(country).append(",");
}
buffer.deleteCharAt(buffer.lastIndexOf(",")); // To remove leading comma
countrieswithComma= buffer.toString();
System.out.println(countrieswithComma);

Output:

Java,Spring,Hibernate,Python,C

References:

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment