Search code examples
javaapache-commonsutility-method

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


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

Solution

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

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