×

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

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

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

Java String hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Deadlock Prevention and avoidance in Java

This tutorial will discuss deadlock prevention and Avoidance in Java programming language. Introduction Multithreading in Java includes deadlock. We can multitask by running several threads concurrently in the multithreading environment. Deadlock occurs...

4 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 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 Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.