Grails Cookbook - A collection of tutorials and examples

Java Split String Into ArrayList

There is a method that splits a String into an array of substrings given a specific delimiter, and this is the Java split() method. Converting a Java String into ArrayList using this method is essential and can be useful in many cases. Let's observe and study the given examples below for a deeper understanding.

Using new ArrayList()

Some situations can be intimidating if we cannot manipulate the list using ArrayList. Now let's try adding or removing elements to which the example above can't do, because of the fixed-size of the result.

An effective alternative is this approach. Observe the codes below:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class JavaSplitStringIntoArrayListEx {
   public static void main(String[] args) {
      String theStr = "A,B,C";
      String[] theArr = theStr.split(",");
      List<String> theList = new ArrayList<String>(Arrays.asList(theArr));
      theList.add("D");
      System.out.println(theList);
   }
}
Notice what we did there, we passed the item to the constructor of the ArrayList using the Arrays.asList(), and we added one item to the variable theList, resulting to a normal mutable object. Check out the output below:
[A, B, C, D]

Using Arrays.asList

One simple solution is to convert the String array to an ArrayList using the static utility method Arrays.asList(). Check out the program below:
import java.util.Arrays;
import java.util.List;
public class JavaSplitStringIntoArrayListEx {
   public static void main(String[] args) {
      String theStr = "X,Y,Z";
      String[] theArr = theStr.split(",");
      List<String> theList = Arrays.asList(theArr);
      System.out.println("The output of the code is: " + theList);
   }
}
The result should give you a fixed-size List backed by the array.
The output of the code is: [X, Y, Z]

Own Solution

Check out the simple implementation through solving manually:
import java.util.ArrayList;
import java.util.List;
public class JavaSplitStringIntoArrayListEx {
   public static void main(String[] args) {
      String theStr = "W,X,Y,Z";
      String[] theArr = theStr.split(",");
      List<String> theList = new ArrayList<String>();
      for (String item : theArr) {
         theList.add(item);
      }
      System.out.println(theList);
   }
}
What the program does is it manually loops the array list and append theArr into the ArrayList. This is also one way of doing Java Split String Into ArrayList.

Notes

There are other ways to solve thins problem, what we showed above are just some ways to do it.