Java Program to Convert the ArrayList into a string and vice versa

Java Program to Convert the ArrayList into a string and vice versa

In this example, we will learn to convert the arraylist into a string and vice versa in Java.

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Convert the Arraylist into a String

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    ArrayList<String> languages= new ArrayList<>();

    // Add elements in the array list
    languages.add("Java");
    languages.add("Python");
    languages.add("JavaScript");
    System.out.println("ArrayList: " + languages);

    // convert the arraylist into a string
    String arraylist = languages.toString();
    System.out.println("String: " + arraylist);

  }
}

Output

ArrayList: [Java, Python, JavaScript]
String: [Java, Python, JavaScript]

In the above example, we have created an arraylist named languages. Notice the line,

languages.toString();

Here, the toString() method converts arraylist into a string. The entire arraylist is converted as a single string.

Note: We can also convert the arraylist into a string array. To learn more, visit Java ArrayList to Array Conversion.


Example 2: Convert ArrayList to String Using join()

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    ArrayList<String> languages= new ArrayList<>();

    // Add elements in the array list
    languages.add("Java");
    languages.add("Python");
    languages.add("JavaScript");
    System.out.println("ArrayList: " + languages);

    // convert the arraylist into a string
    String arraylist = String.join(", ", languages);
    System.out.println("String: " + arraylist);

  }
}

Output

ArrayList: [Java, Python, JavaScript]
String: Java, Python, JavaScript

In the above example, we have used the join() method of the String class to convert the arraylist into a string. To learn more, visit Java String join().


Example 3: Convert a String to ArrayList

import java.util.ArrayList;
import java.util.Arrays;

class Main {
  public static void main(String[] args) {

    // create a string
    String str = "Java, JavaScript, Python";
    System.out.println("String: " + str);

    // convert the string into an array
    String[] arr = str.split(",");

    // create an arraylist from the string
    ArrayList<String> languages = new ArrayList<>(Arrays.asList(arr));
    System.out.println("ArrayList: " + languages);
  }
}

Output

String: Java, JavaScript, Python
ArrayList: [Java,  JavaScript,  Python]

In the above example, we have created a string named str. We have used the split() method to convert the given string into an array. To learn more about splitting a string, visit Java String split().

Notice the expression,

Arrays.asList(arr)

The asList() method converts the string array into an arraylist.