Java API to convert Array to CSV

Anand Hemmige picture Anand Hemmige · Jul 18, 2012 · Viewed 22.9k times · Source

Suppose I have an array of int, float, string etc. Is there any utility API (e.g. Commons, Guava) that will give me a comma separated string?

Like so,

int[] a = {1,2,3,4,5}. 
String s = magicAPI.getCSV(a); // s == "1,2,3,4,5";

Answer

assylias picture assylias · Jul 18, 2012

For this simple use case, you can simply join the strings with comma. If you use Java 8:

String csv = String.join(",", yourArray);

otherwise commons-lang has a join() method:

String csv = org.apache.commons.lang3.StringUtils.join(yourArray, ",");