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

Question:

Possible Duplicates:
What’s the best way to build a string of delimited items in Java?
Java: convert List<String> to a join()d string

In Java, given a collection, getting the iterator and doing a separate case for the first (or last) element and the rest to get a comma separated string seems quite dull, is there something like str.join in Python?

Extra clarification for avoiding it being closed as duplicate: I’d rather not use external libraries like Apache Commons.

Thanks!

update a few years after…

Java 8 came to the rescue

Asked By: fortran

||

Answers:

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.

Answered By: polygenelubricants

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);
Answered By: MichaƂ Niklas

A compromise solution between not writing extra “utils” code and not using external libraries that I’ve found is the following two-liner:

/* collection is an object that formats to something like "[1, 2, 3...]"
  (as the case of ArrayList, Set, etc.)
  That is part of the contract of the Collection interface.
*/
String res = collection.toString();
res = res.substring(1, res.length()-1);
Answered By: fortran

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));
}
Answered By: BobTurbo

Not in the standard library. It is in StringUtils of commons lang.

Answered By: ILMTitan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.