This post will discuss how to convert a List to a String in Java. The solution should concatenate all items in the List to a String using a separator.

1. Using String.join() method

Since Java 8, you can use the String.join() method to join strings together using the specified separator. It only works on a List of type String. Here’s how the code will look like:

Download  Run Code

Output:

A, B, C, D

2. Using Stream API

Java 8 Stream API provides the joining collector that can concatenate the elements of a stream, separated by the specified delimiter. Its usage is demonstrated below:

Download  Run Code

Output:

1, 2, 3, 4

3. Using Apache Commons Lang

Apache Commons Lang StringUtils class provides the join() method which can concatenate list elements together with a specified separator, as shown below:

Download Code

Output:

1, 2, 3, 4

4. Using Guava

If you prefer Guava to Apache Commons Lang, you might want to check out the flexible Joiner class. The following code demonstrates its usage by creating a Joiner, configuring the separator, and specifying the collection to be joined.

Download Code

Output:

1, 2, 3, 4

5. Using toString() method

If you just need to print the string representation of the list, you can do so by calling the toString() on your list. This is demonstrated below:

Download  Run Code

Output:

[1, 2, 3, 4]

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