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

Converting an ArrayList to a string and vice versa is a common task in Java programming.

In this tutorial, we will explore how to convert an ArrayList to a string and vice versa using Java.


Converting ArrayList to String

To convert an ArrayList to a string in Java, we can use the StringBuilder class.

The StringBuilder class provides a method called append() that can be used to append elements to the string.

Here’s how to convert an ArrayList to a string:

import java.util.ArrayList;

public class ArrayListToString {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("Hello");
        list.add("World");
        String str = String.join(" ", list);
        System.out.println(str);
    }
}

In the above code, we first create an ArrayList of Strings and add two elements to it.

We then use the String.join() method to join the elements of the ArrayList into a string.

The first parameter of the join() method is the delimiter that separates the elements in the resulting string.

In this case, we use a space character as the delimiter.

Converting String to ArrayList

To convert a string to an ArrayList in Java, we can use the split() method of the String class.

The split() method splits the string into an array of substrings based on a delimiter.

Here’s how to convert a string to an ArrayList:

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

public class StringToArrayList {
    public static void main(String[] args) {
        String str = "Hello World";
        ArrayList<String> list = new ArrayList<String>(Arrays.asList(str.split(" ")));
        System.out.println(list);
    }
}

In the above code, we first create a string containing two words separated by a space character.

We then use the split() method to split the string into an array of substrings based on the space delimiter.

We then create an ArrayList using the Arrays.asList() method and pass the array of substrings as the argument.


Conclusion

Converting an ArrayList to a string and vice versa is a simple task in Java.

By using the StringBuilder class and the join() method, we can easily convert an ArrayList to a string.

Similarly, by using the split() method of the String class and the Arrays.asList() method, we can convert a string to an ArrayList.