×

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:

  1. Using the toString method over a list, we convert the given list into a string that includes the commas and the square brackets.
  2. To remove the square brackets, we use the substring method so that we can eliminate the first and last brackets included in the String.
  3. 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.


Related Topics

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.