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 🙂