How to Join Strings with Delimiter in Java


How can we join multiple strings together with a delimiter in Java?

There are multiple approaches we can take.

1. StringJoiner

In Java 8, we can use StringJoiner.

StringJoiner joiner = new StringJoiner(",");
joiner.add("a").add("b").add("c");
String joined = joiner.toString(); // "a,b,c"

The constructor of StringJoiner() will accept the delimiter.

We can then call add() on this StringJoiner instance.

Finally, we can call toString() to obtain the delimited string.

2. String.join()

In Java 8, we can also use String.join() to achieve the same functionality.

The first parameter of String.join() is the delimiter.

The subsequent parameters are the elements in the string, as seen in the String.join(CharSequence delimiter, CharSequence... element) documentation.

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

We can also pass in an iterable, as seen in the String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements) documentation.

List<String> s = Arrays.asList("a", "b", "c");
String joined = String.join(",", s); // "a,b,c"

3. StringUtils.join()

Apache Commons Lang provides a StringUtils.join() method to join strings together with a separator.

List<String> s = Arrays.asList("a", "b", "c");
String joined = StringUtils.join(s, ","); // "a,b,c"

Here, the second parameter is our delimiter, and the first is an array.

4. Guava’s Joiner

Guava’s Joiner API is also available to us to join strings with a delimiter.

List<String> s = Arrays.asList("a", "b", "c");
String joined = Joiner.on(",").join(s); // "a,b,c"

We place our delimiter as parameter of Joiner.on().

Our array of strings is then passed into the join() method.

5. Join Strings using Streams

We can also use Java 8 Streams to join strings.

List<String> s = Arrays.asList("a", "b", "c");
String joined = 
   s.stream()
    .collect(Collectors.joining(","));

If the list as nulls, we can use String::valueOf.

List<String> s = Arrays.asList("a", "b", "c");
String joined = 
   s.stream()
    .map(String::valueOf)
    .collect(Collectors.joining(","));