Java split string into list examples

Simple split of string into list

If you want to split string into a list you can use simply the method split(""). It can be used:

  • without one parameter - regex or the character that is used as separator
  • with two parameters - separator and the second one is limit which shows the limit for spliting
        String sampleString = "Python2 Python3 Python Numpy";
        
        String[] items = sampleString.split(" ");
        List<String> itemList = Arrays.asList(items);
        System.out.println(itemList);
        
        String[] itemsLimit = sampleString.split(" ", 2);
        List<String> itemListLimit = Arrays.asList(itemsLimit);
        System.out.println(itemListLimit);

the result is:

[Python2, Python3, Python, Numpy]

[Python2, Python3 Python Numpy]

Java split string by comma

Java split string by comma or any other character use the same method split() with parameter - comma, dot etc

        String sampleString = "Python2, Python3, Python, Numpy";

        String[] items = sampleString.split(",");
        List<String> itemList = Arrays.asList(items);
        System.out.println(itemList);
        System.out.println(itemList.size());

        String[] itemsLimit = sampleString.split(",", 2);
        List<String> itemListLimit = Arrays.asList(itemsLimit);
        System.out.println(itemListLimit);
        System.out.println(itemListLimit.size());

the result is:

[Python2, Python3, Python, Numpy]
4
[Python2, Python3, Python, Numpy]
2

Split multi-line string into a list (per line)

We can use the same string method split and the special character for new line '\n\r'. Since Java 8 we can define mutliline strings with String.join():

import java.util.Arrays;
import java.util.List;

public class StringTest {
    public static void main(java.lang.String[] args) {
        String separator = System.getProperty("line.separator");
        String sampleString = String.join(
                separator,
                "First line",
                "Second line",
                "Third line",
                "Forth line"
        );

        String[] items = sampleString.split(separator);
        //String[] items = sampleString.split("\r\n"); //you can use the special symbols \r\n
        List<String> itemList = Arrays.asList(items);
        System.out.println(itemList);
    }
}

the result is:

[First line, Second line, Third line, Forth line]

Java split string by comma with ArrayList

Another option is to use ArrayList

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {
   public static void main(String[] args) {
   
      String sampleString = "Python2, Python3, Python, Numpy";
      
      String[] items = sampleString.split(",");
      List<String> itemList = new ArrayList<String>(Arrays.asList(items));
      
      System.out.println(itemList);
   }
}

the result is:

Python2, Python3, Python, Numpy

Related Article