Signup/Sign In
PUBLISHED ON: JANUARY 27, 2021

How to Convert String to ArrayList in Java

In this post, we are going to convert a string to ArrayList using Java code. The string is a sequence of characters and a class in Java while the ArrayList is an implementation class of list interface.

Suppose, we have a URL string that consists of a server resource path and separated by some separate symbols, and we want to get it as ArrayList. So, we need to perform this conversion.

To convert string to ArrayList, we are using asList(), split() and add() methods. The asList() method belongs to the Arrays class and returns a list from an array.

The split() method belongs to the String class and returns an array based on the specified split delimiter.

Here, we have several examples to illustrate the string to ArrayList conversion process. See the examples below.

Time for an Example:

Let's take an example to get an Arraylist from a string. Here, we are using the split() method to get an array of strings and then converting this array into a list using the asList() method.

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

public class Main {
	public static void main(String[] args){
		String msg = "StudyTonight.com/tutorial/java/string";
		System.out.println(msg);
		// string to ArrayList
		ArrayList<String> list = new ArrayList<>(Arrays.asList(msg.split("/")));
		list.forEach(System.out::println);	
	}
}


StudyTonight.com/tutorial/java/string
StudyTonight.com
tutorial
java
string

Example 1

If we have an array of strings then we don't need to split() method. We can directly pass this array into asList() method to get ArrayList. See the example below.

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

public class Main {
	public static void main(String[] args){
		String[] msg = {"StudyTonight.com","tutorial","java","string"};
		System.out.println(msg.length);
		// string[] to ArrayList
		ArrayList<String> list = new ArrayList<>(Arrays.asList(msg));
		list.forEach(System.out::println);	
	}
}


4
StudyTonight.com
tutorial
java
string

Example 2

Let's take another example to get ArrayList, Here, we are using add() method to add string array elements to the ArrayList by traversing. This is easiest and simple for beginners.

import java.util.ArrayList;

public class Main {
	public static void main(String[] args){
		String[] msg = {"StudyTonight.com","tutorial","java","string"};
		System.out.println(msg.length);
		// string[] to ArrayList
		ArrayList<String> list = new ArrayList<>();
		for (String string : msg) {
			list.add(string);
		}
		System.out.println(list);	
	}
}


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



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.