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
.
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 new Java file in the ~/project
directory named StringToArrayList.java
:
$ cd ~/project
$ touch StringToArrayList.java
$ touch StringToArrayList.java
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;
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 = "LabEx.com/tutorial/java/string";
ArrayList<String> list = new ArrayList<>(Arrays.asList(msg.split("/")));
System.out.println(list);
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 = {"LabEx.com","tutorial","java","string"};
ArrayList<String> list = new ArrayList<>(Arrays.asList(msg));
System.out.println(list);
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 = {"LabEx.com","tutorial","java","string"};
ArrayList<String> list = new ArrayList<>();
for (String string : msg) {
list.add(string);
}
System.out.println(list);
Save the changes to your file and compile the code:
$ javac StringToArrayList.java
Run the code:
$ java StringToArrayList
You should see the following output in the terminal for each of the above examples respectively:
[LabEx.com, tutorial, java, string]
[LabEx.com, tutorial, java, string]
[LabEx.com, tutorial, java, string]
The output shows that the string has been successfully converted to an ArrayList
using different methods.
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.