In this java tutorial, you will learn how to convert a String to an ArrayList.
Input: 22,33,44,55,66,77
Delimiter: , (comma)
Output: ArrayList with 6 elements {22, 33, 44, 55, 66, 77}
Input: Welcome to BeginnersBook
Delimiter: ” ” (whitespace)
Output: ArrayList with 3 elements {“Welcome”, “to”, “BeginnersBook”}
The steps to convert string to ArrayList:
1) First split the string using String split() method and assign the substrings into an array of strings. We can split the string based on any character, expression etc.
2) Create an ArrayList and copy the element of string array to newly created ArrayList using Arrays.asList() method. This method returns a list created based on the elements of the specified array.
Program to Convert String to ArrayList
In this java program, we are converting a comma separated string to arraylist in java. The input string consists of numbers and commas. We are splitting the string based on comma (,) as delimiter to get substrings. These substrings are assigned to ArrayList as elements.
import java.util.ArrayList; import java.util.List; import java.util.Arrays; public class JavaExample { public static void main(String args[]){ String num = "22,33,44,55,66,77"; String str[] = num.split(","); List<String> al = new ArrayList<String>(); al = Arrays.asList(str); for(String s: al){ System.out.println(s); } } }
Output:
22 33 44 55 66 77
Note: In the above example, the delimiter is comma however we can split the string based on any delimiter. For example: if the string is “hello hi namaste bye” then we can split the string using whitespace as delimiter like this –
Here we have provided whitespace as delimiter String str[] = num.split(" ");
Leave a Reply