Collections Java String Handling RegEx

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. Example also shows how to convert comma separated string to ArrayList in various ways.

How to convert comma separated string to ArrayList in Java?

Comma separated string values can be converted to ArrayList or List in below given ways.

1) Convert comma separated string to ArrayList using split method and regular expression

Split string using split method and then convert resulting array to List using asList method of 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 spaces, you can use "\\s*,\\s*" regular expression pattern where,

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

Output

2) Convert comma separated string to ArrayList using Java 8 stream

If you are using Java 8, you can use stream to convert comma separated String to ArrayList as given below.

Output

Alternatively, you can use Pattern class to convert comma separated string to ArrayList as given below.

Output

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

There are a couple of ways we can convert comma separated string containing numbers to ArrayList of Long as given below.

a) Using split and parseLong methods

You can use split method to split comma separated values to an array of String. Iterate array, convert elements to Long using 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

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

 

Join 1000+ fellow learners! Enter your email address below: