177

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;
Mad-D
  • 4,479
  • 18
  • 52
  • 93
  • If your app involves Spring then it has a utility method [collectionToCommaDelimitedString](http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/util/StringUtils.html#collectionToCommaDelimitedString%28java.util.Collection%29). I wouldn't pull the library in just for that but if you're using it already... – Ian Roberts Apr 04 '13 at 15:37
  • 9
    `List.toString` does it already, just remove the last and the first characters. – Bhesh Gurung Apr 04 '13 at 15:39
  • Including the leading `", "`? – Kijewski Apr 04 '13 at 15:45
  • 9
    Java 8 has [a very straightforward way to do this](https://stackoverflow.com/a/10850885/792238): ```String.join(",", slist);``` – Siddhartha Oct 24 '18 at 23:17
  • 5
    One more candidate: `String string = result.stream().collect(Collectors.joining(", "));` – User Sep 11 '19 at 06:51

3 Answers3

474

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

MrMaavin
  • 1,611
  • 2
  • 19
  • 30
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
  • 21
    StringUtils from Apache Commons Lang (http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join(java.util.Iterator, char)) – Sigrist Feb 08 '14 at 10:46
  • 67
    On Android, you can use TextUtils.join(). – Hemant G Sep 22 '15 at 11:00
  • 2
    Java doesn't support single quotes – Passionate Engineer Oct 18 '15 at 15:21
  • 11
    @PassionateDeveloper single quotes are used for `char`s in Java – itsthejash Nov 13 '15 at 14:05
  • @itsthejash learn something new everyday... thanks. – Nick H Mar 23 '16 at 03:06
  • 14
    @HemantG For the Android users: `TextUtils.join()` expects the parameters in a different order than `StringUtils`. It's `TextUtils.join(delimiter, iterable)`. For example, the code above would be `TextUtils.join(',', slist);` [Source](https://developer.android.com/reference/android/text/TextUtils.html) – peitek Jun 19 '16 at 19:44
  • 1
    In java 8, String listString = slist.stream().map(Object::toString) .collect(Collectors.joining(", ")); – Thirumal Oct 20 '17 at 10:21
  • 5
    If you're using Java 8 and you don't want to use the streams api then you can simply do `String.join(",", slist);` – Ram Patra Aug 08 '18 at 13:25
10

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
Kijewski
  • 25,517
  • 12
  • 101
  • 143
  • 3
    Be aware that if Set is empty, StringBuilder.substring will throw an Exception. – Nier Jul 27 '16 at 09:36
  • 1
    You have to run through the String twice. So it is effectively an N^2 algorithm. Really long strings would perform terribly, and depending on your application open up a DoS attack vector. – SoftwareSavant Oct 12 '17 at 18:59
  • @Kay I do very much. An algorithm whose run time increases logarithmically as a function of the number of objects it operates on. Why did I miscalculate somehow? Did I misread your code? in it you go through the same string 2 times, the first to count the total the second to append the string and the separator. Imagine instead of a set of three you had a set of 3 million? Can you imagine how long the run-time of that solution is? – SoftwareSavant Oct 16 '17 at 21:03
  • 1
    Well, I stand corrected. Your right. In your example you don't loop for each element in the string. You literally just run against the length twice, which would be constant. Way to keep me honest. Keep up the good work. – SoftwareSavant Oct 16 '17 at 22:58
4

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

Dan D.
  • 32,246
  • 5
  • 63
  • 79