views:

79

answers:

3

Is there something like the following in Apache Common Lang or Spring Utils or do you write your own Util method for this?

List<String> list = new ArrayList<String>();
list.add("moo");
list.add("foo");
list.add("bar");

String enumeratedList = Util.enumerate(list, ", ");

assert enumeratedList == "moo, foo, bar";

I remember the use of implode in php, this is what i search for java.

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
+3  A: 

You can use StringUtils.join(Object[] array, String delimiter) (from commons-lang) in the following way:

String enumeratedList = StringUtils.join(list.toArray(), ", ");
Bozho
Thank you, overlooked that in the API.
codedevour
While I like bozho's solution, I see no reason not to create a simple `for` loop and do this yourself (takes 3-4 lines of code). I mean, if you haven't included `commons-lang` in your project thus far, would you include it only for a tool you can write yourself for one minute? ;-)
dimitko
@dimitko: Because 1 line is less than 3-4. It's more readable, less error-prone and once you have the library included you can used it "everywhere".
Willi
true words willi.
codedevour
Just pointed out it's not worth including a library for a single usage in the project. And if you already include it, why not use it all over? Couldn't agree more. ;)
dimitko
+2  A: 

It's pretty trivial to inplement if you don't want a dependency on commons-lang. It's also not great to convert a List to an Array simply to join it again into a String. Instead just iterate over your collection. Even better than using Collection is using Iterable which handles anything which can be iterator over (even some sort of stream or Collection of unknown length).

import java.util.Arrays;
import java.util.Iterator;

public class JoinDemo {
  public static String join(String sep, Iterable<String> i) {
    StringBuilder sb = new StringBuilder();
    for (Iterator<String> it = i.iterator(); it.hasNext();) {
      sb.append(it.next());
      if (it.hasNext())
        sb.append(sep);
    }
    return sb.toString();
  }

  public static void main(String[] args) {
    System.out.println(join(",", Arrays.asList(args)));
  }
}

Example:

# javac JoinDemo.java
# java JoinDemo a b c
a,b,c
Mark Renouf
+1  A: 

Google Collections provides the Joiner class, which can be used like this:

public class Main {

    public static void main(String[] args) {
        List<String> list = Lists.newLinkedList();
        list.add("1");
        list.add("2");
        list.add("3");
        System.out.println(Joiner.on(", ").join(list));
    }

}
Jared Russell