开发者

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

This question already has answers here: Closed 12 years ago.

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) elemen开发者_运维百科t 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


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));
}


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);


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.


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);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜