JavaDevNotes.com

Java Split String Into ArrayList Examples

The split() method of the String class splits a String into an array of substrings given a specific delimiter. Here are examples on how to convert the result of the Split Method into an ArrayList.

Arrays.asList Example

The simplest way to convert the output of the Java String Split, which is a String array, to an ArrayList is to use the static utility method Arrays.asList(). Here is an example code:

import java.util.Arrays;
import java.util.List;
public class Test {
   public static void main(String[] args) {
      String sampleString = "Cat,Dog,Elephant";
      String[] items = sampleString.split(",");
      List<String> itemList = Arrays.asList(items);
      System.out.println(itemList);
   }
}

The resulting ArrayList is a fixed-size List backed by the array. The output of the code is this:
[Cat, Dog, Elephant]

new ArrayList Example

The first example is not ideal when you want to manipulate the resulting list. For example: add or remove elements. This is because of the fixed-size nature of the result list. A better approach is this:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
   public static void main(String[] args) {
      String sampleString = "Cat,Dog,Elephant";
      String[] items = sampleString.split(",");
      List<String> itemList = new ArrayList<String>(Arrays.asList(items));
      itemList.add("Fox");
      System.out.println(itemList);
   }
}
As you could see, the result of the Arrays.asList() is passed to the constructor of the ArrayList. The result is a normal mutable object. This is more efficient if you wish to manipulate the result later. Here is the resulting output of the code:
[Cat, Dog, Elephant, Fox]

Hard Code Example

If you wish to solve the requirement manually, here is a sample implementation:
import java.util.ArrayList;
import java.util.List;
public class Test {
   public static void main(String[] args) {
      String sampleString = "Cat,Dog,Elephant";
      String[] items = sampleString.split(",");
      List<String> itemList = new ArrayList<String>();
      for (String item : items) {
         itemList.add(item);
      }
      System.out.println(itemList);
   }
}
The code manually loops the array list and add the items to the ArrayList. This is a crude way of doing Java Split String Into ArrayList.

String Tutorials And Examples