Convert a String into an ArrayList in Java

Exercise:

Write a Java Program to convert a string into an arraylist.

Click Here to View the Solution!
import java.util.ArrayList;
import java.util.Arrays;

public class StringToArraylist {
    public static void main(String[] args) 
        String str = "Java, JavaScript, Python, CPP , C, Swift";
        System.out.println("String: " + str);

        // convert the string into an array
        String[] arr = str.split(",");

        // create an arraylist from the string
        ArrayList<String> languages = new ArrayList<>(Arrays.asList(arr));
        System.out.println("ArrayList: " + languages);
    }
}
Click Here to View the Output!
 String: Java, JavaScript, Python, CPP , C, Swift
 ArrayList: [Java,  JavaScript,  Python,  CPP ,  C,  Swift]
Click Here to View the Explanation!
  • In this program, first a String called str is created which contains a sequence of characters separated by commas in between them.
  • This string str is then printed onto the screen.
  • Str is then split using the split() method with , passed as its parameter. This means that the string is split where comma is present and the characters before the split are stored as an element in the String array arr.
  • The array arr is then converted into an arraylist called languages using the asList() method of the Arrays class, where arr is passed as a parameter.
  • Languages is then printed onto the screen.

%d bloggers like this: