Best way to convert list to comma separated string in java

353,625

Solution 1

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

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

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

Share:
353,625

Related videos on Youtube

Mad-D
Author by

Mad-D

Updated on January 17, 2022

Comments

  • Mad-D
    Mad-D over 2 years

    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;
    
    • Ian Roberts
      Ian Roberts about 11 years
      If your app involves Spring then it has a utility method collectionToCommaDelimitedString. I wouldn't pull the library in just for that but if you're using it already...
    • Bhesh Gurung
      Bhesh Gurung about 11 years
      List.toString does it already, just remove the last and the first characters.
    • kay
      kay about 11 years
      Including the leading ", "?
    • Siddhartha
      Siddhartha over 5 years
      Java 8 has a very straightforward way to do this: String.join(",", slist);
    • Khan
      Khan over 4 years
      One more candidate: String string = result.stream().collect(Collectors.joining(", "));
  • Sigrist
    Sigrist about 10 years
    StringUtils from Apache Commons Lang (commons.apache.org/proper/commons-lang/apidocs/org/apache/…‌​, char))
  • Hemant G
    Hemant G over 8 years
    On Android, you can use TextUtils.join().
  • Passionate Engineer
    Passionate Engineer over 8 years
    Java doesn't support single quotes
  • itsthejash
    itsthejash over 8 years
    @PassionateDeveloper single quotes are used for chars in Java
  • Nick H
    Nick H about 8 years
    @itsthejash learn something new everyday... thanks.
  • peitek
    peitek almost 8 years
    @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
  • Nier
    Nier almost 8 years
    Be aware that if Set is empty, StringBuilder.substring will throw an Exception.
  • SoftwareSavant
    SoftwareSavant over 6 years
    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
    SoftwareSavant over 6 years
    @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
    SoftwareSavant over 6 years
    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.
  • Thirumal
    Thirumal over 6 years
    In java 8, String listString = slist.stream().map(Object::toString) .collect(Collectors.joining(", "));
  • Ram Patra
    Ram Patra over 5 years
    If you're using Java 8 and you don't want to use the streams api then you can simply do String.join(",", slist);