This post will discuss how to convert a list to a string in Java. The solution should join elements of the provided list into a single string with a given delimiter. The solution should not add a delimiter before or after the list.

1. Using StringBuilder

The idea is to loop through the list and concatenate each list element to the StringBuilder instance with the specified delimiter. Finally, we return the string representation of the StringBuilder. Note that the solution should deal with trailing delimiters’ characters.

Download  Run Code

2. Using Java 8 and above

The above solution is not recommended for Java 8 and above. From Java 8 onward, we can use the static join() method of the String class, which joins strings together with a specified delimiter.

Download  Run Code

 
Note that the above method works only on a list of strings. If our list is not of string type, a joining collector can be used, as shown below:

Download  Run Code

 
This is equivalent to:

Download  Run Code

3. Using Guava’s Joiner Class

Like the String.join() method, Guava provides Joiner class, which can joins elements of a list using a delimiter.

Download Code

4. Using Apache Commons Lang

Finally, we can also use the Apache Commons Lang library for our purpose. StringUtils class offers the join() method, which takes the list and separator. It joins the elements of the provided list into a single string containing the provided list of elements.

Download Code

That’s all about converting a List to a Java String.