Convert List to String in Java
Sometimes, we need to convert a list of characters into a string. A string is a sequence of characters, so we can easily form a string from a character array. We have some special strings, such as a palindrome string (a string that is the same as the original string after reversing it). In order to reverse a string, we need to convert the string into a char array for reversing all the chars of string, and after reversing the char array, we need to convert it into a string.
In Java, we have several ways through which we can convert a list into a string are as follows:
1. Using StringBuilder class
We have a very simple way to convert a list into a string, i.e., by using the StringBuilder class. We iterate the list of char using for loop and generate a new string with the help of StringBuilder.
Let’s implement the code for converting a list into a string by using the StringBuilder class:
ConvertListToStringExample1.java
Output:
2. Using Joiner class
Like StringBuilder, we have one more class, i.e., Joiner class, through which we can convert a list into a string. We use the join() method of the Joiner class, which is also known as the Guava method. The join() method joins the pieces into the specified text as an array and returns the results as a string.
Let’s implement the code for converting a list into a string by using the Joiner class:
We are using the maven project, so it is required to add the following dependency in our POM.xml file.
ConvertListToStringExample2.java
Output:
3. Using List.toString(), String.substring() and String.replaceAll() methods
In this way of converting a list into a string, we use three methods of List and String classes. We use three methods to perform the following operations:
- We use the toString() method of the list to convert the list into a string. The return string will also contain opening/closing square brackets and commas.
- We use the substring() method to get rid of opening/closing square brackets.
- We use the replaceAll() method to replace all the commas and spaces with blank or null.
Let’s implement the code for converting a list into a string by using the toString(), substring(), and replaceAll() methods:
ConvertListToStringExample3.java
Output:
4. Using Collectors in Java
It is the last way to convert a list into a string. We use it rarely because here, we use stream API with collectors, which is available only in Java8.
Let’s implement the code for converting a list into string by using the stream API with Collectors.
ConvertListToStringExample3.java
Output:
In all the above-discussed ways, we have frequently used the StringBuilder class for converting a list into a string.