33

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

Community
  • 1
  • 1
fortran
  • 74,053
  • 25
  • 135
  • 175
  • 3
    See [What's the best way to build a string of delimited items in Java?](http://stackoverflow.com/questions/63150/whats-the-best-way-to-build-a-string-of-delimited-items-in-java), and try one of the join methods from Apache [StringUtils](http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html). – Matthew Flaschen Jul 13 '10 at 10:32
  • 2
    Just write an utility to do that. Be careful the join should be done with StringBuffer or StringBuilder for hight performance. – qrtt1 Jul 13 '10 at 10:32
  • Great question, I also found that whole missing-trailing separator problem very tedious for years ! Never knew about the str.join thing in Python - very useful shortcut! ... str.join(",",["thanks","very","much"]) ... – monojohnny Jul 13 '10 at 10:40
  • 1
    @monojohnny You don't need to use it as a class method, the first argument is the implicit *self*, so you can do `",".join(["thanks","very","much"])` instead :-) – fortran Jul 13 '10 at 10:51
  • @Wayne I think it's not worth the hassle xD – fortran Jul 13 '10 at 16:52
  • @fortran - even better cheers! (Albeit a little odd-looking if you didn't know what it was doing, in that way that ternary-ifs are until you get used to them...) – monojohnny Jul 14 '10 at 10:55

5 Answers5

17

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);
Michał Niklas
  • 53,067
  • 18
  • 70
  • 114
15

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));
}
BobTurbo
  • 1,065
  • 1
  • 8
  • 16
  • 1
    Correct. But it would be better if the method could take a Collection argument instead, so it works regardless of implementation. – mahju Jul 13 '10 at 11:23
  • And from force of habit, I was going to say it should take a `Collection extends String>`, but on second thoughts, don't bother. :-) – Andrzej Doyle Jul 13 '10 at 11:25
  • @Andrzej yeah, the first time I noticed that String was final I was really disappointed for all the dirty things that I couldn't do xD – fortran Jul 13 '10 at 16:50
  • You should add a second param that just takes a character and replace "," with it. I'd say you should provide a default argument but that requires you to write another method D:< One of Java's failings, IMO – Wayne Werner Jul 13 '10 at 17:38
  • Yeah I should make it more reusable.. but I can't be bothered now :) I could also do return wordList.substring(0, wordList.length() - 2) or something like that. – BobTurbo Jul 14 '10 at 03:46
9

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.

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • I was under the impression that the same Apache library containing StringBuilder had a `join` function no? But its been a bit since I touched that code, so maybe I misremember... – Petriborg Jul 13 '10 at 10:34
  • 3
    @Petriborg: `java.lang.StringBuilder` is JavaSE, not Apache's. I'm not sure if that answers your question. – polygenelubricants Jul 13 '10 at 10:36
  • @Petriborg StringUtil of apache commmons has join (http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#join%28java.lang.Iterable,%20char%29). – Thomas Jung Jul 13 '10 at 11:22
3

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);
fortran
  • 74,053
  • 25
  • 135
  • 175
  • 2
    I would be wary of using this - the `toString` output isn't guaranteed to have any specific format on `java.util.ArrayList`. It's *unlikely* it would change but that would be entirely legal. It would be safer (and arguably clearer) just to write the few lines of "extra utils code", IMHO. – Andrzej Doyle Jul 13 '10 at 11:24
  • The API specifies that `AbstractCollection`'s toString is formatted as bracketed comma separated strings: http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/util/AbstractCollection.html#toString%28%29 – fortran Jul 14 '10 at 07:23
0

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

ILMTitan
  • 10,751
  • 3
  • 30
  • 46