This post will discuss how to join elements of a list in Java separated by a delimiter.

1. Using Collectors.joining() method

A simple and efficient way to join elements of a list by a delimiter in Java is using Java 8 features such as Stream API. We can use the stream() method to convert the list into a stream of strings, then use the map() method to apply any transformation to each element (such as calling toString()), and then use the collect() method with the Collectors.joining() collector to join all the elements by a delimiter. For example:

Download  Run Code

2. Using String.join() method

The String.join() is a static method introduced in Java 8 that takes a delimiter and an iterable of strings (such as a list) as arguments and returns a single string with all the elements joined by the delimiter. For example:

Download  Run Code

3. Using StringBuilder Class

Another way to join elements of a list is using the StringBuilder class. The idea is to create an instance of the StringBuilder class and append each element of the list to it, along with the delimiter. We can use a loop to iterate over the list and check if the current element is the last one or not. If it is not the last one, we can append the delimiter after it. Otherwise, we can skip the delimiter. Finally, we return the string representation of the StringBuilder. For example, to join a list of strings with a hyphen as a delimiter, we can write:

Download  Run Code

4. Using StringJoiner Class

In the previous approach, we’re appending the delimiter to StringBuilder for every pair of consecutive elements in the list. From Java 8 onward, we can use the StringJoiner class, that allows us to create a string with a specified delimiter, prefix, and suffix. We can use the add() method to append each element of the list to the string joiner, and then use the toString() method to get the final string. For example:

Download  Run Code

5. Using Guava’s Joiner Class

Similar to the StringJoiner class, Guava library Joiner class is designed to tackle a similar problem. The basic usage of the Joiner class is to create an instance with a specified delimiter using the on() method, and then call the join() method with the list of elements to be joined. For example:

Download Code

 
The Joiner class also provides some useful methods to handle null values, such as skipNulls() and useForNull(). The skipNulls() method returns a new Joiner instance that skips over any null elements in the input. The useForNull() method returns a new Joiner instance that replaces any null elements with a given string. For example:

Download Code

6. Using Apache Commons Lang

Apache Commons Lang is another external library that provide methods to join elements of a list by a delimiter. For example, we can use the StringUtils.join() method from Apache Commons Lang like this:

Download  Run Code

That’s all about joining elements of a list in Java separated by a delimiter.