Explain Codes LogoExplain Codes Logo

How to convert comma-separated String to List?

java
split
java-streams
regex
Alex KataevbyAlex Kataev·Sep 18, 2024
TLDR

Effortlessly switch a comma-separated String into a List with the split method and Arrays.asList:

List<String> list = Arrays.asList("item1,item2,item3".split(","));

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:

// Like space wizards, we vanish the spaces List<String> list = Arrays.asList("item1 , item2 , item3".split("\\s*,\\s*"));

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:

// Like a supermarket trolley, this arraylist is ready for whatever you add List<String> list = new ArrayList<>(Arrays.asList("item1,item2,item3".split(",")));

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:

// Meet Splitter, the slicing samurai List<String> list = Lists.newArrayList( Splitter.on(",") .omitEmptyStrings() .trimResults() .split("item1 , , item2 , item3") );

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:

// Hey look, a new trim spell! List<String> list = Stream.of("item1 , item2 , item3".split(",")) .map(String::trim) .collect(Collectors.toList());

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:

// Say hello to Pattern, your new best friend List<String> list = Pattern.compile("\\s*,\\s*") .splitAsStream("item1 , item2 , item3") .collect(Collectors.toCollection(ArrayList::new));

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.

List<String> list = new ArrayList<>(...);

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:

// Processing strings to count only the living items, not the ghosts List<String> list = Stream.of("🍎, ,🍌,,🍇,🍒".split(",")) .filter(s -> !s.isEmpty()) .map(String::trim) .collect(Collectors.toList());

When limited by old Java versions

Stuck with Java 7 or below? Fear not, you can still sort your items using good old loops:

String[] coins = "🍎,🍌,🍇,🍒".split(","); List<String> coinPiles = new ArrayList<String>(coins.length); for (String coin : coins) { coinPiles.add(coin.trim()); }

A bit of backwards compatibility never hurt anyone!