How to split String by comma in Java - Example Tutorial

In the earlier article, I have shown you how to split String by regular expression and now, you will learn how to split string by comma. Since CSV is a popular format for exporting data, you often need to split a comma-separated String to create an array of individual Strings. Similar to the earlier example, you can use the split() method to accomplish this task. Just pass a "," instead of "\\s+" the regular expression to remove whitespaces, as the regular expression.  The split method will return an array of String, which you can further convert to a list of String. 

If your String contains a leading or trailing whitespace, make sure you trim the String before calling the split() method. 

Also, remember that this method will throw PatternSyntaxException if the regular expression's syntax is invalid. Last but not least this version of the split method is only available from Java 1.4 onwards.

On a related note, if you have just started learning Java, it's always better to use a companion book. This will improve your learning and you will learn more things in less time. You can use Core Java Volume 1, 9th Edition by Cay S. Horstmann is a core book to learn Java. Let's see the example to split a comma-separated String in Java now.



Java Program to split comma Separated String

Here is our sample Java program to demonstrate how you can use the split() method of java.lang.String class to break a CSV string into words. In our example, we have a String where programming languages are separated by the comma. We will convert this into a String array and if you want to convert it into a list, you can.

Since String is immutable in Java, you can not modify the original String. Any modification will result in a new String object. This is, even more important, when your String contains leading or trailing space,  the trim() method will return a new String. 

Make sure you call a split() method on that String, rather than on the original String as shown in our program.

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

/**
 * Java Program to split String by comma.
 * This program demonstrate how you can use the split()
 * method from String class to break a comma separated String
 * into words.
 * 
 * @author WINDOWS 8
 *
 */
public class SplitStringByComma {

    public static void main(String args[]) {

        // You can use the split() method to split a
        // String where words are separated by comma.
        // since split() method expect a regular expression
        // you can pass "," to it as well, as shown below:

        String languages = "Java,JavaScript,C++,Python,Ruby,Scala";

        // splitting String by comma, it will return array
        String[] array = languages.split(",");

        // if you want, you can convert array to ArraList as shown below
        ArrayList<String> list = new ArrayList<>(Arrays.asList(array));

        // let's print input and output
        System.out.println("comma separated String: " + languages);
        System.out.println("array of String: " + Arrays.toString(array));
        System.out.println("list of String: " + list);

        // In case your CSV String contains leading or trailing spaces
        // call trim() before calling split() to avoid leading
        // space on first and last word.

        String CSVWithLeadingSpace = " XBOX,PlayStation,Wii ";
        String[] withoutTrim = CSVWithLeadingSpace.split(",");
        String[] afterTrimming = CSVWithLeadingSpace.trim().split(",");

        System.out.println("CSV String with leading and trailing space: "
                + CSVWithLeadingSpace);
        System.out.println("words without trim: "
                + Arrays.toString(withoutTrim));
        System.out.println("words after trim: "
                + Arrays.toString(afterTrimming));
    }

}

Output
comma separated String: Java,JavaScript,C++,Python,Ruby,Scala
array of String: [Java, JavaScript, C++, Python, Ruby, Scala]
list of String: [Java, JavaScript, C++, Python, Ruby, Scala]
CSV String with leading and trailing space: XBOX,PlayStation,Wii 
words without trim: [ XBOX, PlayStation, Wii ]
words after trim: [XBOX, PlayStation, Wii]

You can see that we have first got the String array returned by the split() method after splitting a comma-separated array. Next, we have converted that into an ArrayList.

Here is a nice slide showing steps to split a String by comma in Java:

How to split a String by comma in Java with example


That's all about how to split the String by comma in Java. You can further convert the String array returned by the split() method to create an ArrayList as shown here. You should also remember to use the trim() method to remove leading and trailing whitespace from the String before splitting, to avoid individual words starts with space or ends with space as shown in the second example.

Related String articles for further Reading
  • How to create an array from ArrayList of String in Java? (solution)
  • The difference between String literal and new() String in Java? (answer)
  • How to use Regular Expression to Search in String? (answer)
  • How to replace characters on String in Java? (solution)
  • The difference between StringBuilder and StringBuffer in Java? (answer)
  • How to find if String is empty in Java? (answer)
  • The difference between String and StringBuffer in Java? (answer)
  • How to count the number of Vowels and Consonants in Java String? (solution)
  • How to convert an array to String in Java? (solution)
  • How to use substring method in Java? (example)
  • How to convert Enumeration type to String in Java? (answer)
  • The best way to compare two Strings in Java? (answer)
  • How to reverse String in place in Java? (answer)
Over to you now, what is your favorite way to split String by comma or a delimiter in Java? String.split() method or a third party library or anything else? 

4 comments:

  1. What about programming for the interfaces?

    List list = ...

    instead of

    ArrayList list = ...

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.