Best way to convert list to comma separated string

2020-02-16 06:08发布

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;

3条回答
Evening l夕情丶
2楼-- · 2020-02-16 06:28

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
查看更多
何必那么认真
3楼-- · 2020-02-16 06:29

From Apache Commons library:

import org.apache.commons.lang3.StringUtils

Use:

StringUtils.join(slist, ',');

Another similar question and answer here

查看更多
霸刀☆藐视天下
4楼-- · 2020-02-16 06:36

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

查看更多
登录 后发表回答