Skip to content

Convert List to String Java Example

Convert List to String Java example shows how to convert list to string in Java. It also shows how to convert ArrayList to string & LinkedList to string using various approaches.

How to convert List to String?

Let’s first create a List using the ArrayList class as given below.

There are several ways using which you can convert List (ArrayList or LinkedList) to a string containing all the list elements.

1. Convert List to String Using toString method of List

The List provides the toString method which prints all the List elements in the following format.

Output

The separator used by the toString method is “, ” to separate the the List elements. Also the list elements are wrapped inside the square brackets ([]).

If you want another separator you can replace the “, ” with the separator you want (such as tab “\t” or blank space ” “) as given below.

Output

If you want to remove the square brackets too, you can use following code.

Output

Here, we have used regular expression pattern “\\[|\\]” to find the square brackets “[” and “]” in the string. Since the “[” and “]” are metacharacters in the a regular expression, we have to escape them with the “\\”. The “|” denotes “or” in regular expression. So basically we are finding “[” or “]” in the string and replacing all of them with an empty string.

Finally, you can change the separator and remove brackets in one statement as given below.

Output

2. Using for loop

You can also use a for loop to loop through each element of a List and generate the string as given below.

Output

Notice the last the “,” after the last element in the output. You can remove it if you want using below given code.

Output

Note: If you are using Java 1.4 or earlier version, use the StringBuffer instead of the StringBuilder class.

3. Using Apache Commons

If you are using the Apache Commons library, the StringUtils class provides the join method which creates a string from the List elements. You can also provide a separator to the join method as given below.

Output

4. Java 8

Finally, if you are using Java 8 or later version, you can use the join method of the String class to join the List elements and convert it to a string as given below. You can provide separator of your choice to the join method.

Output

This example is a part of the Java String tutorial and Java ArrayList tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.