There are many ways to convert a comma-separated string into a list in Java. In this article, we'll look at three different methods to convert a string with a separator to a list.
Convert a comma-separated string to a list using core Java
The
String
class in Java provides
split()
method
to split a string into an array of strings. You can use this method to turn the comma-separated list into an array:
In the above example, we first used the split() method to convert our fruits string into an array of strings. Then, we used the Stream class to convert the array into a list of strings.
An additional benefit of using Java Stream API is that you can perform other operations on the elements of the array before converting them into a list.
Look at the following example that converts a string of numbers into a list of integers using a stream:
Both split() and splitPreserveAllTokens() methods split the string into an array of strings using a delimiter. However, the splitPreserveAllTokens() method preserves all tokens, including the empty strings created by adjoining separators, while the split() method ignores empty strings.
✌️ Like this article? Follow me on
Twitter
and LinkedIn.
You can also subscribe to
RSS Feed.
Buy me a coffee ☕
If you enjoy reading my articles and want to help me out paying bills, please
consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️
Enter the number of coffees below:
I started this blog as a place to share everything I have learned in the last decade. I
write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things
web development.
The newsletter is sent every week and includes early access to clear, concise, and
easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any
time.