How to split a comma-separated string?
Split a string by commas in Java with the split
method:
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:
Feeling listy? Let's convert our array to a List
:
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:
For more modern approach, embrace the magic of Streams:
Regular expressions and trimming spaces
Whitespaces troubling you? Let regular expressions get you out of this sticky situation:
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:
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!
Was this article helpful?