Skip to content

Convert comma separated string to ArrayList in Java example

Convert comma separated string to ArrayList in Java example shows how to convert comma separated string to ArrayList in Java using regular expression (regex) and Java 8 stream.

How to convert comma separated string to ArrayList in Java?

1) Using the split method and regular expression (regex)

Split string using split method and then convert resulting array to List using the asList method of the Arrays class as given below.

Output

If the values contain space between them along with comma, List elements will have them too. In order to remove the spaces, you can use the "\\s*,\\s*" regular expression pattern where,

Here is the example program to remove the spaces while splitting the string and converting it to the ArrayList.

Output

2) Using the Java 8 stream

If you are using Java 8, you can use a stream as given below.

Output

Alternatively, you can also use the Pattern class as given below.

Output

How to convert comma separated string containing numbers to ArrayList of Long?

a) Using the split and parseLong methods

You can use the split method to split comma separated values to an array of String. Iterate array, convert elements to Long using the parseLong method and add them to ArrayList one by one as given below.

Output

b) Using Java 8 stream

You can also use Java 8 stream as given below.

Output

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.