This question already has an answer here:
这个问题已经有了答案:
- What's the best way to build a string of delimited items in Java? 35 answers
- 在Java中构建分隔项字符串的最佳方式是什么?35的答案
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 个解决方案
#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 = ", "。