Search code examples
javastringsplit

How to split a comma-separated string?


I have a String with an unknown length that looks something like this

"dog, cat, bear, elephant, ..., giraffe"

What would be the optimal way to divide this string at the commas so each word could become an element of an ArrayList?

For example

List<String> strings = new ArrayList<Strings>();
// Add the data here so strings.get(0) would be equal to
// "dog",strings.get(1) would be equal to "cat" a.s.f.

Solution

  • You could do this:

    String str = "...";
    List<String> elephantList = Arrays.asList(str.split(", "));
    

    In Java 9+, create an unmodifiable list with List.of.

    List<String> elephantList = List.of(str.split(", "));  // Unmodifiable list. 
    

    Basically the .split() method will split the string according to (in this case) delimiter you are passing and will return an array of strings.

    However, you seem to be after a List of Strings rather than an array. So the array must be turned into a list. We can turn that array into a List object by calling either Arrays.asList() or List.of.


    FYI you could also do something like so:

    String str = "...";
    ArrayList<String> elephantList = new ArrayList<>(Arrays.asList(str.split(","));
    

    But it is usually better practice to program to an interface rather than to an actual concrete implementation. So I would not recommend this approach.