Is there a utility method to separate a list by given string?

1.7k Views Asked by At

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

There are 3 best solutions below

4
On BEST ANSWER

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

String enumeratedList = StringUtils.join(list.toArray(), ", ");
0
On

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
0
On

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

}