Collections Java String Handling RegEx

Convert String to ArrayList in Java example

Convert String to ArrayList in Java example shows how to convert String to ArrayList in Java. Example also shows how to convert comma separated String to ArrayList using split method and regular expression.

How to convert String to ArrayList in Java?

We are going to convert String to ArrayList such that each word of String will become an element of an ArrayList. Consider below given String object.

We are going to do that by using split method of String class as given below.

Output

How to convert comma separated String to ArrayList?

If 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 ArrayList containing each characters of the String?

There are a couple of way using which you can convert String to ArrayList such that each character of the String becomes an element of an ArrayList.

1) Using charAt and valueOf methods of String class

Loop through the characters of the String and convert each character to String using charAt and valueOf methods of String class as given below.

Output

2) Using Regular Expression

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

Output

Important Note:

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

You can use “(?!^)” pattern instead of 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

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

 

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