Collections RegEx

Convert List to String Java Example

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

How to convert List to String?

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

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

1. Convert List to String Using toString method of List

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

Output

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

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

Output

If you want to remove 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 “[” and “]” are metacharacters in the regular expression, we have to escape them with the “\\”. “|” denotes “or” in regular expression. So basically we are finding “[” or “]” in the string and replacing them with the empty String.

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

Output

2. Convert List to String Using for loop

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

Output

Notice the last “,” 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 StringBuffer instead of StringBuilder class.

3. Convert List to String Using Apache Commons

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

Output

4. Convert List to String in Java 8

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

Output

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.