Is there a direct equivalent in Java for Python's str.join?

Nope there is not. Here is my attempt:

/**
 * Join a collection of strings and add commas as delimiters.
 * @require words.size() > 0 && words != null
 */
public static String concatWithCommas(Collection<String> words) {
    StringBuilder wordList = new StringBuilder();
    for (String word : words) {
        wordList.append(word + ",");
    }
    return new String(wordList.deleteCharAt(wordList.length() - 1));
}

There is nothing in the standard library, but Guava for example has Joiner that does this.

Joiner joiner = Joiner.on(";").skipNulls();
. . .
return joiner.join("Harry", null, "Ron", "Hermione");
// returns "Harry; Ron; Hermione"

You can always write your own using a StringBuilder, though.


For a long time Java offered no such method. Like many others I did my versions of such join for array of strings and collections (iterators).

But Java 8 added String.join():

String[] arr = { "ala", "ma", "kota" };
String joined = String.join(" ", arr);
System.out.println(joined);