Thursday, March 16, 2017

How to Convert an Array to Comma Separated String in Java

The simplest way to convert an array to comma separated String is to create a StringBuilder, iterate through the array, and add each element of the array into StringBuilder after appending comma. You just need Java 1.5 for that, even if you are not running on Java 5, you can use StringBuffer in place of StringBuilder. The joining of String has got even easier in JDK 8, where you have got the join() method right in the String class itself. The join() method takes a delimiter and a source, which can be array or collection and returns a String where each element is joined by a delimiter. If you want to create a CSV string, just pass comma as a delimiter. Btw, these two methods are not the only way to create a comma separated String from an array, you can also use Apache Commons or Spring framework's utility class to do the same.

Now the question comes, why do you need to convert an array to a comma-separated String? Well, there can be many situations but I'll give you mine. Sometimes back, I was writing some JDBC code to store some fields into the database. One of the fields was String array which needs to be stored in a VARCHAR column, and I don't want to store the string returned by the Arrays.toString() method.

The best option was to store comma separated values and then I looked into JDK API for any method which can do that, there wasn't any. So, I quickly wrote one as seen in the first example. Later, I did a little bit of research and come up with four different ways to convert a String array to comma separated String in Java.

4 Ways to Convert String Array to Comma Separated String

Here are my four examples of converting a String array to CSV text. Though you can use the same technique and code to create CSV string from any array e.g. int array, float array or an object array, provided your object has a meaningful String representation.

1) Using Plain Java
This is the simplest way to accomplish the task. All you need to do is write a method which accepts a String array, loop through the array, and appends each element into StringBuilder. Once done, return the String from StringBuilder by calling the toString() method.

Here is one of such method:

public static String toCSV(String[] array) {
        String result = "";

        if (array.length > 0) {
            StringBuilder sb = new StringBuilder();

            for (String s : array) {

            result = sb.deleteCharAt(sb.length() - 1).toString();
        return result;

One of the thing which I don't like about this code is that I need to delete the last character because when you iterate over an array, you end up adding a comma after the last element unless you are checking its last element in each iteration, which is a simple waste of CPU. Do you know any way to make this code better? perhaps by removing the last line of deleting last character.

2) Using  Java 8
This is the most elegant way to convert an array to String in Java. The only catch is that you need to be on JDK 1.8, which is fine for writing test code but not many companies are using JDK 8 for production code yet.

The join() method is overloaded and allows you to join multiple String by leveraging the varargs argument feature. Just pass a number of String and the delimiter you want to combine them, as shown below

String message = String.join("-", "Java", "is", "best"); // "Java-is-best"

But, the version we will use here is the other one, which accepts an Iterable and a delimiter. Since array implements Iterable in Java (remember enhanced for loop), you can use this method to convert an array or collection to delimited String as shown below:

String csv = String.join(",", new String[]{"a", "b"}); // a,b

Here is the Java program to demonstrate how to join Strings in Java from array:

import java.util.Arrays;

 * Java Program to join Strings using a delimeter

public class Java8Demo {

    public static void main(String args[]) {

        String[] supportedPhones = {"iPhone", "Samsung Galaxy", "iPad"};
        String models = String.join(",", supportedPhones);

        System.out.println("array: " + Arrays.toString(supportedPhones));
        System.out.println("string: " + models);



array: [iPhone, Samsung Galaxy, iPad]
string: iPhone,Samsung Galaxy,iPad

Java 8 is full of such new features which will make coding much more pleasant. If you have yet to start with Java 8 then take some time to read Java SE 8 for Really Impatient by Cay S. Horstmann, one of the best books to learn new features of Java 8 including lambdas, stream, new date and time and several others.

How to convert array to comma separated String in Java

3) Using Apache Commons
The third option is to use the Apache Commons library. This is a general purpose library which provides many utility functions, remember we have used it in past for checking blank or empty String. Most of the time you will find that your project already using this library. If that's the case then just use the StringUtils.join() method to convert a String array to CSV string as shown below

StringUtils.join(cities, ','); 

Similar to Java 8 join method, you can also define your own delimiters e.g. pipe, colon or tab.

4) Using Spring Framework
Spring is one of the most popular Java framework and most of the new development  I have done uses Spring for their dependency injection feature. If you happen to use the Spring framework like many others than you can use it's StringUtils class to convert an array to String as shown below. It's very similar to the example, I have explained earlier for converting a collection to String in Java.

All you need to is use the org.springframework.util.StringUtils.arrayToCommaDelimitedString(String[] array) method. You can pass String array and it will return a CSV String.

That's all about how to convert an array to a comma-separated String in Java. Ideally, you should not use any third-party library for such a simple task but if you are already using it then it also doesn't make sense to reinvent the wheel. Use the first option if you are not using Apache Commons or Spring Framework, use the second option if you are running on Java 8 and use the third or fourth option if you already dependent on Apache commons or Spring framework.

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Algorithms and Data Structures - Part 1 and 2
Data Structures in Java 9 by Heinz Kabutz

No comments :

Post a Comment