This post will discuss how to convert comma-separated String to list in Java.

1. Using Arrays.asList with split() method

The idea is to split the string using the split() method and pass the resultant array into the Arrays.asList() method, which returns a fixed-size List backed by an array. To get a mutable ArrayList, we can further pass the fixed-size list to the ArrayList constructor.

Download  Run Code

2. Using Guava Library

Another good alternative is to use the Splitter class from the Guava library to split the string, as shown below. This returns an Iterable instead of an array, which we can pass to Lists.newArrayList(). It creates a mutable ArrayList instance containing all elements of the Iterable. This method is preferred if we need to add or remove elements later, or some of the elements can be null.

Download Code

3. Using Java 8

From Java 8 onward, we can use Stream. The idea is to split the string using the split() method, convert the array into the stream, and then collect all the input elements into a new list using the Collectors.toList() method.

Download  Run Code

 
This is equivalent to:

Download  Run Code

 
Note that Collectors.toList() doesn’t offer any guarantee on the type of list returned. To get the desired Collection, we can use toCollection() method provided by the Collectors class that can accept desired constructor method reference like ArrayList::new or LinkedList::new.

Download  Run Code

4. Using splitAsStream() method

We can also use the splitAsStream() method, which returns the stream computed by splitting the input around matches of the given pattern.

Download  Run Code

That’s all about converting comma-separated String to List in Java.