This question already has answers here:
Closed 6 years ago.
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;
From Apache Commons library:
import org.apache.commons.lang3.StringUtils
Use:
StringUtils.join(slist, ',');
Another similar question and answer here
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
The Separator
you are using is a UI component. You would be better using a simple String sep = ", "
.