Java Programming Examples Tutorial Index

Java String Programs

This Java program is used to demonstrates split strings into ArrayList.



The steps involved are as follows:

  • Splitting the string by using Java split() method and storing the substrings into an array.
  • Creating an ArrayList while passing the substring reference to it using Arrays.asList() method.

Example:

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);
        }
    }
}

Program Output:

99
42
55
81
79
64
22

Explanation:

In this Java program, the java.util.Arraylist package has been imported. This package provides resizable array and it uses the List interface. It provides various methods for manipulating the size of the array which is used internally for storing the list. Java.util.Arrays is used to deal with arrays of different types. It contains a static factory which provides arrays to be viewed as lists.

The a class is declared name StringtoArrayList inside which the main() is defined. The statement:

String strings = "99, 42, 55, 81, 79, 64, 22";

defines that using the String class, a string type of variable name strings is declared and initialized with a set of values.

Then comes the String array str[] which implements the default split() method. This method has two alternatives and is used to splits the associated string around matches of that given regular expression. It splits a string into sub string and returns it as a new array.

Now another statement where a List is created with the name nl and that object of the List is assigned a ArrayList type of value by converting it from string, which is str[] here. And then using enhanced For loop, prints all the converted valued. This is how a simple string value gets converted to ArrayList.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram