Convert a String to Character array in Java

In this post, we will see how to convert a String to Character array in Java.


 

1. Naive

Naive solution would be to use a regular for loop to read all characters of the string and assign it to a Character array one by one.

Java

Download   Run Code

Output:

[J, a, v, a]

2. Java 8

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

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

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

Java

Download   Run Code

Output:

[J, a, v, a]

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

Java

Download   Run Code

Output:

[J, a, v, a]

3. Using Apache Commons Lang

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

Java

Download

Output:

[J, a, v, a]

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.

Java

Download   Run Code

Output:

[J, a, v, a]

 
Related Post: Convert character array to a String in Java

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz