Sameek Mishra Sameek Mishra - 1 month ago 7
Java Question

How to convert a String into an ArrayList?

How to convert a string into an ArrayList. In my string, I can have an arbitrary number of words which I want added into an ArrayList object, e.g.:

String s = "a,b,c,d,e,.........";

Answer

Try something like

List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));

Demo:

String s = "lorem,ipsum,dolor,sit,amet";

List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));

System.out.println(myList);  // prints [lorem, ipsum, dolor, sit, amet]

This post has been rewritten as an article here.

Comments