Algorithm


Convert ArrayList to String:

  1. Initialize an ArrayList of the desired type.
  2. Add elements to the ArrayList.
  3. Create a StringBuilder or StringBuffer to build the string representation.
  4. Iterate through the ArrayList and append each element to the StringBuilder or StringBuffer, separated by a delimiter if needed.
  5. Convert the StringBuilder or StringBuffer to a String using the toString() method.

Convert String to ArrayList:

  1. Initialize an empty ArrayList of the desired type.
  2. Obtain the input string that represents the ArrayList.
  3. Split the input string into individual elements based on a delimiter if needed.
  4. Iterate through the split elements and add them to the ArrayList.
  5. Handle any necessary type conversions based on the data type of the ArrayList.

 

Code Examples

#1 Code Example- Convert the Arraylist into a String

Code - Java Programming

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);

  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
ArrayList: [Java, Python, JavaScript]
String: [Java, Python, JavaScript]

#2 Code Example- Convert ArrayList to String Using join()

Code - Java Programming

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);

  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
ArrayList: [Java, Python, JavaScript]
String: Java, Python, JavaScript

#3 Code Example- Convert a String to ArrayList

Code - Java Programming

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);
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
String: Java, JavaScript, Python
ArrayList: [Java, JavaScript, Python]
Advertisements

Demonstration


Java Programing Example to Convert the ArrayList into a string and vice versa-DevsEnv