Convert String to ArrayList

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to convert a string to an ArrayList in Java. We will use the asList(), split(), and add() methods to convert a string into an ArrayList.

Create a Java file

Create a new Java file in the ~/project directory named StringToArrayList.java:

$ cd ~/project
$ touch StringToArrayList.java
$ touch StringToArrayList.java

Import ArrayList and Arrays classes

We need to import the ArrayList and Arrays classes to use them in our code. Add the following lines at the beginning of your StringToArrayList.java file:

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

Convert string to ArrayList using split() method

We can use the split() method to split the string into an array of substrings based on a specified delimiter. Then we can convert the array to an ArrayList using Arrays.asList() method. Add the following code inside the main() method:

String msg = "StudyTonight.com/tutorial/java/string";
ArrayList<String> list = new ArrayList<>(Arrays.asList(msg.split("/")));
System.out.println(list);

Convert string array to ArrayList using asList() method

If we have an array of strings, we can directly pass it into the asList() method to get an ArrayList. Add the following code inside the main() method:

String[] msg = {"StudyTonight.com","tutorial","java","string"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(msg));
System.out.println(list);

Convert string array to ArrayList using add() method

We can also add each element of the string array to the ArrayList one by one using the add() method. Add the following code inside the main() method:

String[] msg = {"StudyTonight.com","tutorial","java","string"};
ArrayList<String> list = new ArrayList<>();
for (String string : msg) {
    list.add(string);
}
System.out.println(list);

Compile and run the code

Save the changes to your file and compile the code:

$ javac StringToArrayList.java

Run the code:

$ java StringToArrayList

Verify the output

You should see the following output in the terminal for each of the above examples respectively:

[StudyTonight.com, tutorial, java, string]
[StudyTonight.com, tutorial, java, string]
[StudyTonight.com, tutorial, java, string]

The output shows that the string has been successfully converted to an ArrayList using different methods.

Summary

In this lab, you learned how to convert a string to an ArrayList in Java using the asList(), split(), and add() methods. You can choose the method that best suits your needs based on the input data.

Other Java Tutorials you may like