Advertisement
Advertisement


Best way to convert list to comma separated string in java


Question

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;
2013/04/04
1
148
4/4/2013 3:44:07 PM

Accepted Answer

From Apache Commons library:

import org.apache.commons.lang3.StringUtils

Use:

StringUtils.join(slist, ',');

Another similar question and answer here

2017/05/23
403
5/23/2017 12:03:05 PM

You could count the total length of the string first, and pass it to the StringBuilder constructor. And you do not need to convert the Set first.

Set<String> abc = new HashSet<String>();
abc.add("A");
abc.add("B");
abc.add("C");

String separator = ", ";
int total = abc.size() * separator.length();
for (String s : abc) {
    total += s.length();
}

StringBuilder sb = new StringBuilder(total);
for (String s : abc) {
    sb.append(separator).append(s);
}

String result = sb.substring(separator.length()); // remove leading separator
2013/04/04

The Separator you are using is a UI component. You would be better using a simple String sep = ", ".

2013/04/04