×

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without problems. We have a few unique strings, consisting of a palindrome string (a string that can be the same after reversing). To reverse a given string, we need to change the String to a character array of all the characters of the String, and after reversing the char array, we need to transform it into a string.

We can convert a list to a string in java in many ways, some are as follows:

1. Using StringBuilder class

Although, there are many ways to transform a list into a string, by using the StringBuilder class, it can be done easuly. The List can be iterated using for loop and generate a new string with the assistance of StringBuilder.

By using a simple program, we can implement the code for transforming a list into a string by using the StringBuilder class:

Example

// import of the packages 
  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Scanner;  
  
// create class ConvertListToString which is used for converting the input char list to string  
class ConvertListToString{  
    // main method()  
    public static void main(String[] args)  
    {  
        // decalaring variabes and list to store characters 
        int sizeofList;  
        String str;  
        List<Character> charList = new ArrayList<Character>();  
          
        // scanner class created for taking input from user  
        Scanner sc = new Scanner(System.in);  
          
        System.out.println("Enter the list size.");  
        sizeofList= sc.nextInt();  
         for(int i = 0; i < sizeofList; i++) {  
            System.out.println("ENTER THE char["+i+"]: ");  
            charList.add(sc.next().charAt(0));  
        }  
// closing of the scanner class
        sc.close();  
          
        // displaying the list of character elements  
        System.out.println("List: " + charList);  
  
        // An object is created for string builder class  
        StringBuilder builder = new StringBuilder();  
  
        //visiting each character in the character list  
        for (Character cha : charList) {  
            builder.append(cha);  
        }  
  
        // object is converted into string  
        str = builder.toString();  
  
        //String is displayed 
        System.out.println("List is coverted to string: " + str);  
    }  
}  

Output

How to convert list to String in java

2: Using List.toString(), String.substring() and String.replaceAll() methods

Converting the List into the String, we use these 3 methods. The following three methods we use the following operations:

1. The toString () method converts the List into a String. The return value will contain square brackets and commas(,).

2. The substring() method can escape from opening or closing square brackets.

3. replace() all method is used to replace all spaces and commas.

We can implement a code for converting lists to strings using these methods.

Example

// required packages are imported 
import java.util.ArrayList;  //reading list elements
import java.util.List;  
import java.util.Scanner;  
  
// A class listtostring is created to convert list into string by using all the three methods   
class Main {  
    // start of main() method
    public static void main(String[] args)  
    {  
        //declaring variables and list
        int size;  
        String str;  
        List<Character> charList = new ArrayList<Character>();  
          
        // Scanner class is used for reading dynamic input from user
        Scanner sc = new Scanner(System.in);  
          
        System.out.println("Enter the list.");  
           size = sc.nextInt();  
                for(int i = 0; i < size; i++) {  
            System.out.println("ENTER char["+i+"]: ");  
            charList.add(sc.next().charAt(0));  
        }  
          
        // scanner class object is closed  
        sc.close();  
          
        // displaying the character list elements
        System.out.println("List: " + charList);  
  
  
        // used for converting list to string by three methods  
        str = charList.toString()  
                .substring(1, 3 * charList.size() - 1)  
                .replaceAll(", ", "");  
  
        //String displaying  
        System.out.println("List is converted from string: " + str);  
    }  
}  

 Output

How to convert list to String in java

3. Collectors in java

It is also one of the ways to convert a given list into a string. Stream collectors are used for this method, which is available under the version of Java8.

This can be implemented by a simple program using API collectors in java.

Example

// packages import section  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Scanner;  
import java.util.stream.Collectors;  
  
// class ConvertListToString is created to convert list to string using api collectors
class ConvertListToString {  
    // main method 
    public static void main(String[] args)  
    {  
        // variables and list are declared 
        int size;  
        String str;  
        List<Character> charList = new ArrayList<Character>();  
          
        // Scanner class is created for taking input at runtime
        Scanner c = new Scanner(System.in);  
          
        System.out.println("Enter the size of the list.");  
        size = c.nextInt();  
          
        for(int i = 0; i < size; i++) {  
            System.out.println("ENTER char["+i+"]: ");  
            charList.add(c.next().charAt(0));  
        }  
          
        // Ending of scanner class object  
        c.close();  
          
        // displaying the elements of the character list  
        System.out.println("List: " + charList);  
      // converting of list to string by using collect() method
        str = charList.stream()  
                .map(String::valueOf)  
                .collect(Collectors.joining());  
  
        // the output string is displayed
        System.out.println("Converted string: " + str);  
    }  
}

Output

How to convert list to String in java

Hence in these ways, a list can be converted to a string. Among these, one of the most used ways are the StringBuffer method from which a List can be converted to String. Additionally, you can use any method accordingly.


Related Topics

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

JAR File in Java

What is a JAR File? JAR stands for Java Archive. It is a file format mainly used to combine many Java class files and the corresponding metadata and resources into one...

4 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

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

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.