Algorithm


  1. import java.util.ArrayList;: Imports the ArrayList class from the java.util package.
    import java.util.List;: Imports the List interface from the java.util package.
    import java.util.Arrays;: Imports the Arrays class from the java.util package.
    public class StringtoArrayList {: Defines a class named StringtoArrayList.
    public static void main(String args[]){: The entry point of the program, where execution begins.
    String strings = "99,42,55,81,79,64,22";: Defines a string named strings containing a comma-separated list of numbers.
    String str[] = strings.split(",");: Splits the strings string into an array of strings using "," as the delimiter.
    List nl = new ArrayList();: Creates an ArrayList named nl. Note that the type is not specified for nl, so it can hold any type of object.
    nl = Arrays.asList(str);: Converts the array str into a fixed-size list and assigns it to the nl ArrayList.
    for(String s: nl){: Iterates over each element in the ArrayList.
    System.out.println(s);: Prints each element of the ArrayList on a new line.

Code Examples

#1 Java programing is used to strings into ArrayList.

Code - Java Programming

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

public class StringtoArrayList {
    public static void main(String args[]){
        String strings = "99,42,55,81,79,64,22";
        String str[] = strings.split(",");
        
        List nl = new ArrayList();
        nl = Arrays.asList(str);
        for(String s: nl){
            System.out.println(s);
        }
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
99
42
55
81
79
64
22

#2 Example to get an Arraylist from a string

Code - Java Programming

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);	
	}
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
StudyTonight.com/tutorial/java/string
StudyTonight.com
tutorial
java
string

#3 Eaxmple-directly pass this array into asList() method to get ArrayList

Code - Java Programming

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);	
	}
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
4
StudyTonight.com
tutorial
java
string
Advertisements

Demonstration


Java program to Convert String to ArrayList-DevsEnv