Saturday, September 25, 2021

How to Convert an Array to Comma Separated String in Java - Example Tutorial

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 the 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 an 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 the 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 a String array that 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.

Also, basic knowledge of essential data structure is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to fill the gaps in your understanding.





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 an array, for example, 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 that 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 such method:

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

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

            for (String s : array) {
                sb.append(s).append(",");
            }

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

One of the things 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 or deleting the last character.





2.  Using  Java 8

This is the most elegant way to convert an array to a 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 the 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);

    }

}

Output
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 book 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.




3. Using Apache Commons

The third option is to use the Apache Commons library. This is a general-purpose library that 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 a CSV string as shown below

StringUtils.join(cities, ','); 

Similar to Java 8 String.join() method, you can also define your own delimiters like pipe, colon, or tab.

How to Convert an Array to Comma Separated String in Java - Example Tutorial





4. Using Spring Framework

Spring is one of the most popular Java frameworks 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 then you can use its 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 do is use the org.springframework.util.StringUtils.arrayToCommaDelimitedString(String[] array) method. You can pass the String array and it will return a CSV String.

String message = StringUtils.arrayToCommaDelimitedString(
 new String[] {"-", "Java", "is", "best"}); // "Java-is-best"




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 are already dependent on Apache commons or Spring framework.

Other Java Array and Programming tutorials you may like:
  • 10 Points about Array in Java? (must-know facts)
  • How to declare and initialize a two-dimensional array in Java? (solution)
  • Write a program to find missing numbers in a sorted array? (algorithm)
  • How to search elements in an array in Java? (solution)
  • How do find the largest and smallest numbers in an array? (solution)
  • How to find prime factors of an integer in Java? (solution)
  • How to find the top two maximum on integer array in Java? (solution)
  • How to sort the array using a bubble sort algorithm? (algorithm)
  • Write a program to find the first non-repeated characters from String in Java? (program)
  • How to check if a number is binary in Java? (answer)
  • Write a Program to Check if a number is Power of Two or not? (program)
  • Write a program to check if a number is Prime or not? (solution)
  • How to calculate factorial using recursion in Java? (algorithm)
  • How to check if LinkedList contains any cycle in Java? (solution)
  • Write a method to count occurrences of a character in String? (Solution)
  • How to find a Fibonacci sequence up to a given number? (solution)
  • How to check if a number is an Armstrong number or not? (solution)
  • Write a method to remove duplicates from ArrayList in Java? (Solution)
  • Write a program to check if a number is a Palindrome or not? (program)
  • Write a program to check if Array contains duplicate numbers or not? (Solution)
  • How to find a largest prime factor of a number in Java? (solution)
  • Write a Program to remove duplicates from the array without using Collection API? (program)
  • How to reverse String in Java without using API methods? (Solution)
  • Write a method to check if two String are Anagram of each other? (method)
Thanks for reading this article so far. If you like this Java Array Tutorial to convert an array to CSV string then please share it with your friends and colleagues. If you have any questions or doubt then please let us know and I'll try to find an answer for you.  

P. S. - If you want to learn essential data structures like an array, linked list, binary tree, queue, stack, and graph and looking for free resources like free Udemy courses then I also suggest you to checkout my list of 10 free Data Structure and Algorithms courses to start with. In this post, I have shared the best free algorithms courses from Udemy, Coursera, and Educative for Java developers. 

1 comment :

Anonymous said...

Thanks a lot. its help.

Post a Comment