Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java API to convert Array to CSV

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";
like image 376
Anand Hemmige Avatar asked Jul 18 '12 16:07

Anand Hemmige


1 Answers

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, ",");
like image 161
assylias Avatar answered Oct 22 '22 08:10

assylias