Explain Codes LogoExplain Codes Logo

How to split a comma-separated string?

java
string-manipulation
list-conversion
regular-expressions
Nikita BarsukovbyNikita Barsukov·Feb 21, 2025
TLDR

Split a string by commas in Java with the split method:

String str = "apple,banana,cherry"; // Our fruit salad in progress... String[] items = str.split(",");

Here, items is an array holding separated elements, like apple. If your items have spaces around them, use ", " as delimiter.

For split and trim at the same time:

// Now even the whitespace won't escape String[] items = str.split("\\s*,\\s*");

Feeling listy? Let's convert our array to a List:

// An array a day keeps the OutOfBoundsException away List<String> itemList = Arrays.asList(items);

That was your cook's recipe. Now let's dive deeper into our kitchen!

Advanced use cases

Conversion to List

Post-split, if you want to tap into the power of List, convert the array:

String[] items = str.split(","); // Array in disguise List<String> itemList = new ArrayList<>(Arrays.asList(items));

For more modern approach, embrace the magic of Streams:

List<String> itemList = Arrays.stream(str.split(",")) .collect(Collectors.toList());

Regular expressions and trimming spaces

Whitespaces troubling you? Let regular expressions get you out of this sticky situation:

// String gymnastics - splits and trims at once String[] items = str.split("\\s*,\\s*");

The regex \\s*,\\s* will trim those annoying spaces lurking around your commas.

The ghost element trap

Watch out for the empty string lurking in the shadows:

String str = "apple,,cherry"; // Where did banana go?? String[] items = str.split(",");

The array reads an empty string where the banana used to be!

Code efficiency and readability

Make your code readable. A well-read code is a well-fed code, even better than a bucket of fried chicken. Also, don't waste time preprocessing strings, your code's performance is at stake!