Algorithm
Convert ArrayList to String:
- Initialize an ArrayList of the desired type.
- Add elements to the ArrayList.
- Create a StringBuilder or StringBuffer to build the string representation.
- Iterate through the ArrayList and append each element to the StringBuilder or StringBuffer, separated by a delimiter if needed.
- Convert the StringBuilder or StringBuffer to a String using the
toString()
method.
Convert String to ArrayList:
- Initialize an empty ArrayList of the desired type.
- Obtain the input string that represents the ArrayList.
- Split the input string into individual elements based on a delimiter if needed.
- Iterate through the split elements and add them to the ArrayList.
- 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
ArrayList: [Java, Python, JavaScript]
String: [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
ArrayList: [Java, Python, JavaScript]
String: 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
String: Java, JavaScript, Python
ArrayList: [Java, JavaScript, Python]
ArrayList: [Java, JavaScript, Python]
Demonstration
Java Programing Example to Convert the ArrayList into a string and vice versa-DevsEnv