Wednesday 16 March 2016

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.
Read more »

No comments:

Post a Comment