Best way to convert list to comma separated string in java

JavaStringListCollectionsSet

Java Problem Overview


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;

Java Solutions


Solution 1 - Java

Since Java 8:

String.join(",", slist);

From Apache Commons library:

import org.apache.commons.lang3.StringUtils

Use:

StringUtils.join(slist, ',');

Another similar question and answer here

Solution 2 - Java

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

Solution 3 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMad-DView Question on Stackoverflow
Solution 1 - JavaBobTheBuilderView Answer on Stackoverflow
Solution 2 - JavakayView Answer on Stackoverflow
Solution 3 - JavaDan D.View Answer on Stackoverflow