This post will discuss how to convert a string to a Character array in Java.

1. Naive solution

A naive solution is to use a regular for-loop to read all the characters in the string and assign them to a Character array one by one.

Download  Run Code

2. Using Java 8

Java 8 does not provide any char stream, but we can get an IntStream (a stream of ints) of characters using the String.chars() method when dealing with strings.

After obtaining the IntStream of characters, we need to box it to Stream<Character>. We can do this by casting char using lambda ch -> (char) ch inside mapToObj(), which will then automatically boxed to Character.

Finally, the toArray(T[]) method can be used to dump the Stream into a newly allocated Character array.

Download  Run Code

 
Another option to get an IntStream is to use the String.codePoints() method, as shown below:

Download  Run Code

 
This is equivalent to:

Download  Run Code

3. Using Apache Commons Lang

Apache Commons Lang ArrayUtils class provides the toObject() method, which can convert a char array to Character array. To get a char array from string, we can use String.toCharArray().

Download Code

4. Convert string to list of Character

Sometimes we want to convert string to List<Character>. We can use Guava’s Lists.charactersOf() to do so.

Download Code

That’s all about converting a String to a Character array in Java.

 
Related Post:

Convert a char array to a String in Java