Best way to convert list to comma separated string in java

Mad-D picture Mad-D · Apr 4, 2013 · Viewed 318k times · Source

I have Set<String> result & would like to convert it to comma separated string. My approach would be as shown below, but looking for other opinion as well.

List<String> slist = new ArrayList<String> (result);
StringBuilder rString = new StringBuilder();

Separator sep = new Separator(", ");
//String sep = ", ";
for (String each : slist) {
    rString.append(sep).append(each);
}

return rString;

Answer

BobTheBuilder picture BobTheBuilder · Apr 4, 2013

From Apache Commons library:

import org.apache.commons.lang3.StringUtils

Use:

StringUtils.join(slist, ',');

Another similar question and answer here