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 thesplit()
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 theString array arr
.- The
array arr
is then converted into anarraylist
calledlanguages
using theasList()
method of the Arrays class, wherearr
is passed as a parameter. Languages
is then printed onto the screen.