Skip to content

Convert String to ArrayList in Java example

Convert String to ArrayList in Java example shows how to convert String to ArrayList in Java using the split method and regular expression.

How to convert String to an ArrayList in Java?

We are going to convert string such that each word of the string will become an element of an ArrayList. We are going to do that by using the split method of the String class as given below.

Output

How to convert comma separated String to an ArrayList?

If a string contains comma separated values which you want to convert to an ArrayList such that each value becomes an element of an ArrayList, use below given code.

Output

How to convert String to an ArrayList containing each character of the String?

1) Using charAt and valueOf methods of String class

Loop through the characters of the string and convert each character to string using the charAt method. Finally, add each character string to an ArrayList using the add method of an ArrayList and valueOf method of the String class as given below.

Output

2) Using Regular Expression

Use regular expression along with the split method of the String class to split the string by empty strings as given below.

Output

Important Note:

If you are using Java 7 or below then the first element of an ArrayList is a blank or empty string. However, If you are using Java 8 or later, the first element returned from the split method is no longer an empty String.

You can use the “(?!^)” pattern instead of an empty string to correct the problem where,

When used along with the split method, the regular expression pattern “(?!^)” means that split all the characters of the string except for the start of the string (i.e. first character of the String).

Output

This example is a part of the Java String tutorial and Java ArrayList 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.