The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

Use the Google Guava API's join method:

Joiner.on(",").join(collectionOfStrings);

Note: This answers was good when it was written 11 years ago, but now there are far better options to do this more cleanly in a single line, both using only Java built-in classes or using a utility library. See other answers below.


Since strings are immutable, you may want to use the StringBuilder class if you're going to alter the String in the code.

The StringBuilder class can be seen as a mutable String object which allocates more memory when its content is altered.

The original suggestion in the question can be written even more clearly and efficiently, by taking care of the redundant trailing comma:

    StringBuilder result = new StringBuilder();
    for(String string : collectionOfStrings) {
        result.append(string);
        result.append(",");
    }
    return result.length() > 0 ? result.substring(0, result.length() - 1): "";

I just looked at code that did this today. This is a variation on AviewAnew's answer.

collectionOfStrings = /* source string collection */;
String csList = StringUtils.join(collectionOfStrings.toArray(), ",");

The StringUtils ( <-- commons.lang 2.x, or commons.lang 3.x link) we used is from Apache Commons.

Tags:

Sql

Java

String