A quick and easy way to join array elements with a separator (the opposite of split) in Java [duplicate] A quick and easy way to join array elements with a separator (the opposite of split) in Java [duplicate] arrays arrays

A quick and easy way to join array elements with a separator (the opposite of split) in Java [duplicate]


Using Java 8 you can do this in a very clean way:

String.join(delimiter, elements);

This works in three ways:

1) directly specifying the elements

String joined1 = String.join(",", "a", "b", "c");

2) using arrays

String[] array = new String[] { "a", "b", "c" };String joined2 = String.join(",", array);

3) using iterables

List<String> list = Arrays.asList(array);String joined3 = String.join(",", list);


I prefer Google Collections over Apache StringUtils for this particular problem:

Joiner.on(separator).join(array)

Compared to StringUtils, the Joiner API has a fluent design and is a bit more flexible, e.g. null elements may be skipped or replaced by a placeholder. Also, Joiner has a feature for joining maps with a separator between key and value.