Convert List To Comma Separated String In Java

Recently I came across a small requirement where I would receive country codes in list of String from User Interface and in the back-end i had to convert it into comma separated String and store in database. In this article, we will explore what are all the ways to convert given list to comma separated String in java.

Convert List To Comma Separated String

1. Using StringUtils from Apache Commons Library

We can use Apache Commons Lang‘s StringUtils class. It provides StringUtils.join(Iterable<?> iterable, char separator) method to do so.

[su_box title=”Apache Commons Lang Library” box_color=”#faf62b” title_color=”#151111″]
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
[/su_box]

Example:

List<String> listCountries = Arrays.asList("US", "IN", "NP","NL");
String csv=StringUtils.join(listCountries, ',');
System.out.println(csv);   //US,IN,NP,NL

2. Using String.join(-,-) method in Java 8

Since java 8, join(-,-) method has been introduced. Pass a delimiter and Iterable to join(-,-) method as follows.

Example:

List<String> listCountries = Arrays.asList(“US”, “IN”, “NP”,”NL”);
String csv=String.join(“,”, listCountries);
System.out.println(csv);    //US,IN,NP,NL

3. Using stream in Java 8

By using java.util.stream.Collectors.joining(CharSequence delimiter), we can achieve our result as follows.

Example:

List<String> listCountries = Arrays.asList("US", "IN", "NP","NL");
String csv=listCountries.stream().collect(Collectors.joining(","));
System.out.println(csv);    //US,IN,NP,NL

4. Using Java 7

There are various ways to achieve it in java 7, out of which two implementation are given below.

I hope you will enjoy these various approach on converting list to comma separated String in java. Stay tuned for similar interesting articles.

Be the first to comment

Leave a Reply