Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert list to comma separated string in java [duplicate]

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;
like image 255
Mad-D Avatar asked Oct 09 '22 16:10

Mad-D


People also ask

How do you convert an ArrayList to a comma separated string in Java?

We can convert ArrayList to a comma-separated String using StringJoiner which is a class in java. util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

How do you add a comma separated string to a list in Java?

Split the String into an array of Strings using the split() method. Now, convert the obtained String array to list using the asList() method of the Arrays class.

How do I convert a list to a string in Java?

We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.


3 Answers

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

like image 166
BobTheBuilder Avatar answered Oct 19 '22 20:10

BobTheBuilder


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
like image 29
kay Avatar answered Oct 19 '22 18:10

kay


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

like image 4
Dan D. Avatar answered Oct 19 '22 19:10

Dan D.