×

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 Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Counting sort in Java

An array's elements are sorted using the counting sort method, which counts how many times each distinct element appears in the array. The count is kept in an auxiliary array,...

3 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

How to convert float to String in Java

How to convert float to String in java There are following methods to convert float to String: Convert using Float.toString(float) Convert using String.valueOf(float) Convert using Float.toString(float) The Float class has a static method that returns...

2 minutes read.

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included....

4 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 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.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

Java Calculate Average of List

The list is a linear data structure used in Java to store ordered data collections. Additionally, it accepts duplicate values while maintaining insertion order. It is sometimes necessary to find...

3 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.