Convert List to String in Java
We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string. There are certain unique strings we have, like a palindrome sequence. A string must first be turned into a char array to change all the characters in the String, and then the char array must be turned back into a string.
In this little lesson, we'll go through how to change a List of items into a string. This may come in handy in some circumstances, such as when printing the data to the prompt in a readable format for examination or debugging.
The following are some of the methods we have in Java for turning a list into such a string:
Using StringBuilder class in Java
We have a pretty straightforward method, i.e., employing the StringBuilder class, for turning a list into a string. Using a for loop, we traverse the list of chars, and StringBuilder is used to create a new string.
Let's put the following code into practice to create a string from a list that uses the StringBuilder class:
ListtoString.java
// All the required packages are imported
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// Class ListtoString, which converts the input List to a string, and below is the code
class ListtoString {
// main method starts here
public static void main(String[] args)
{
// Setting up the required variables such as length and output string variable
int length;
String ans;
List list = new ArrayList();
// Object creation for the scanner class using which we take user inputs.
Scanner sc = new Scanner(System.in);
System.out.println("Length of the input char list is :");
length = sc.nextInt();
for(int j = 0; j < length; j++) {
System.out.println("Enter char[" + j + "]: ");
list.add(sc.next().charAt(0));
}
// closing the Scanner class object
sc.close();
// Printing the given list of input
System.out.println("Given input char list :" + list);
// Object creation for the stringbuilder class
StringBuilder sb = new StringBuilder();
// Traversing the char list that is input using for each loop
for (Character ch : list) {
sb.append(ch);
}
// String builder to the string variable using the tostring method
ans = sb.toString();
// Printing the string variable after converting the list
System.out.println("Input list converted to String : " + ans);
}
}
Output
Length of the input char list is :
5
Enter char[0]:
m
Enter char[1]:
a
Enter char[2]:
n
Enter char[3]:
o
Enter char[4]:
j
Given input char list :[m, a, n, o, j]
Input list converted to String : Manoj
Using Java Joiner Class
We have a class called Joiner that works similarly to StringBuilder, allowing us to turn a list into a string. We employ the join() method, sometimes referred to as the Guava method, from the Joiner class. The join() method results are returned as a string after joining the fragments into the given text as an array.
Let's use the Joiner class to implement the following code to transform a list into such a string:
ListtoString1.java
// All the required packages are imported
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.google.common.base.Joiner;
// Class ListtoString1, which converts the input List to a string, and below is the code
class ListtoString1 {
// main method starts here
public static void main(String[] args)
{
// Setting up the required variables such as length and output string variable
int length;
String ans;
List list = new ArrayList();
// Object creation for the scanner class using which we take user inputs.
Scanner sc = new Scanner(System.in);
System.out.println("Length of the input char list is :");
length = sc.nextInt();
for(int i = 0; i < length; i++) {
System.out.println("Enter char[" + i + "]: ");
list.add(sc.next().charAt(0));
}
// closing the Scanner class object
sc.close();
// Printing the given list of input
System.out.println("Given input char list : " + list);
ans = Joiner.on("").join(list);
// Printing the string variable after converting the list
System.out.println("Input list converted to String : " + ans);
}
}
Output
Length of the input char list is :
5
Enter char[0]:
k
Enter char[1]:
u
Enter char[2]:
m
Enter char[3]:
a
Enter char[4]:
r
Given input char list :[k, u, m, a, r]
Input list converted to String : Kumar
Using Java List.toString(), String.substring() and String.replaceAll() methods
This list to string conversion method uses three methods from the List and String objects. The following operations are carried out using three different ways:
- Using the toString method over a list, we convert the given list into a string that includes the commas and the square brackets.
- To remove the square brackets, we use the substring method so that we can eliminate the first and last brackets included in the String.
- We use the replaceAll method to replace all the commas and spaces included with a null.
Below is the code for converting a list into a string using the three methods string() method, substring() method and replaceAll() method and below is the implementation.
ListtoString2.java
// All the required packages are imported
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// Class ListtoString2, which converts the input List to a string, and below is the code
class ListtoString2 {
// main method starts here
public static void main(String[] args)
{
// Setting up the required variables such as length and output string variable
int length;
String ans;
List<Character> list = new ArrayList<Character>();
// Object creation for the scanner class using which we take user inputs.
Scanner sc = new Scanner(System.in);
System.out.println("Length of the input char list is :");
length = sc.nextInt();
for(int i = 0; i < length; i++) {
System.out.println("Enter char[" + i + "]: ");
list.add(sc.next().charAt(0));
}
// closing the Scanner class object
sc.close();
// Printing the given list of input
System.out.println("List: " + list);
// using the three methods string() method, substring() method and replaceAll() //method so as to remove the extra elements from the string that is sqare brackets //and commas.
ans = list.toString()
.substring(1, 3 * list.size() - 1)
.replaceAll(", ", "");
// Printing the string variable after converting the list
System.out.println("Input list converted to String : " + ans);
}
}
Output:
Length of the input char list is :
5
Enter char[0]:
b
Enter char[1]:
i
Enter char[2]:
t
Enter char[3]:
t
Enter char[4]:
u
List: [b, i, t, t, u]
Input list converted to String: bittu
Using Java Collectors
It is the final method of turning a list into such a string. We hardly utilise it because we use the Java 8-only stream API with collectors.
We must convert the Integer to String because of the Collectors. joining() method needs a CharSequence. Even if we don't have knowledge of the class's source code, we can still apply this concept to other classes.
Let's put the code for a list to-string conversion into practice by combining Collectors and the stream API.
ListtoString3.java
// All the required packages are imported
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
// Class ListtoString3, which converts the input List to a string, and below is the code
class ListtoString3 {
// main method starts here
public static void main(String[] args)
{
// Setting up the required variables such as length and output string variable
int length;
String ans;
List list = new ArrayList();
// Object creation for the scanner class using which we take user inputs.
Scanner sc = new Scanner(System.in);
System.out.println("Length of the input char list is :");
length = sc.nextInt();
for(int i = 0; i < length; i++) {
System.out.println("Enter char[" + i + "]: ");
list.add(sc.next().charAt(0));
}
// closing the Scanner class object
sc.close();
// Printing the given list of input
System.out.println("List: " + list);
// utilising the methods join() and collect(), transform a list into a string.
ans = list.stream()
.map(String::valueOf)
.collect(Collectors.joining());
// Printing the string variable after converting the list
System.out.println("Input list converted to String : " + ans);
}
}
Output
Length of the input char list is :
10
Enter char[0]:
a
Enter char[1]:
b
Enter char[2]:
c
Enter char[3]:
d
Enter char[4]:
e
Enter char[5]:
f
Enter char[6]:
g
Enter char[7]:
h
Enter char[8]:
i
Enter char[9]:
j
List: [a, b, c, d, e, f, g, h, i, j]
Input list converted to String: abcdefghij
This article discovered several straightforward methods for changing a List into a String. We have regularly used the StringBuilder class to turn a list into a string in all the methods mentioned earlier.