在java [duplicate]中将列表转换为逗号分隔字符串的最佳方式

时间:2022-01-11 00:18:03

This question already has an answer here:

这个问题已经有了答案:

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.

我设置了 result &想把它转换成逗号分隔的字符串。我的方法如下所示,但是也要寻找其他的意见。

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 个解决方案

#1


315  

From Apache Commons library:

从Apache Commons图书馆:

import org.apache.commons.lang3.StringUtils

Use:

使用:

StringUtils.join(slist, ',');

Another similar question and answer here

这里还有一个类似的问题和答案

#2


6  

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.

您可以首先计算字符串的总长度,并将其传递给StringBuilder构造函数。而且您不需要首先转换设置。

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


3  

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

您正在使用的分隔符是一个UI组件。您最好使用一个简单的字符串sep = ", "。

#1


315  

From Apache Commons library:

从Apache Commons图书馆:

import org.apache.commons.lang3.StringUtils

Use:

使用:

StringUtils.join(slist, ',');

Another similar question and answer here

这里还有一个类似的问题和答案

#2


6  

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.

您可以首先计算字符串的总长度,并将其传递给StringBuilder构造函数。而且您不需要首先转换设置。

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


3  

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

您正在使用的分隔符是一个UI组件。您最好使用一个简单的字符串sep = ", "。