Java program to convert the arraylist into a string and vice versa
Here's a Java program to convert an ArrayList
to a String
and vice versa:
import java.util.ArrayList; import java.util.Arrays; public class ArrayListToString { public static void main(String[] args) { // Convert ArrayList to String ArrayList<String> fruits = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry")); String fruitsString = String.join(",", fruits); System.out.println("ArrayList to String: " + fruitsString); // Convert String to ArrayList String numbersString = "1,2,3,4,5"; ArrayList<String> numbers = new ArrayList<>(Arrays.asList(numbersString.split(","))); System.out.println("String to ArrayList: " + numbers); } }
In this program, we first create an ArrayList
called fruits
containing some strings. We then use the String.join
method to join the elements of the ArrayList
with a separator (a comma in this case) to convert it to a String
. The resulting String
is then printed to the console.
Next, we define a String
called numbersString
containing comma-separated numbers. We use the String.split
method to split the String
into an array of strings, and then create a new ArrayList
containing those strings to convert the String
to an ArrayList
. The resulting ArrayList
is then printed to the console.
You can modify the ArrayList
and String
values to convert different lists to strings and vice versa. Note that if the elements in the ArrayList
or String
contain commas or the separator character, you will need to use a different separator or a different method for joining or splitting the values.