How to convert comma-separated String to List?
Effortlessly switch a comma-separated String into a List with the split
method and Arrays.asList
:
This creates a List
with "item1"
, "item2"
, and "item3"
as elements. However, beware that this list is fixed in size. Like a pie, you cannot add or remove slices after it has been baked.
When spaces make a difference
Sometimes, you don't want spaces around your commas. In such case, adjust the rules of the game with this split
pattern:
The regex \\s*,\\s*
works like a magic wand to make the unwanted spaces disappear.
Choose your own adventure: mutable lists
When a fixed-size list isn't your cup of Java, brew an ArrayList
instead:
Now, your list
can grow and shrink to your heart's content!
When you face the split boss: Guava's Splitter
For complex splitting cases, bring out the big guns with Guava's Splitter:
Bonus powers of Splitter
: you can banish empty entries and gracefully trim results, all without breaking a sweat over regex!
Styling your code with the power of Java streams
Enhance your split move with Java 8's Streams API. This lets you trim spaces while still looking cool:
The Stream
pipeline is like the secret shortcut to readable and efficient code.
Battle with regex using the Pattern class
Looking to directly splash some regex in the Stream API? The Pattern
class is like your secret potion:
Pattern
cleverly leverages regex for splitting and collects the result straight into your ArrayList
.
It’s an age-old question: List or ArrayList?
Programming wisdom advises to declare collections using the interface type (List
), because it's more flexible than the implementation type (ArrayList
). Like choosing a bigger wardrobe, it fits more options for later.
Opt for List<String>
when you don’t really need the special features an ArrayList
provides.
Stand up to the empty strings
An empty string in a comma-separated string is like a ghost—somewhat invisible. Use the power of Java Streams to banish them:
When limited by old Java versions
Stuck with Java 7 or below? Fear not, you can still sort your items using good old loops:
A bit of backwards compatibility never hurt anyone!
Was this article helpful?