Convert a String to a List of Characters in Java

In this post, we will discuss how to convert a string to a list of characters in Java.

 

1. Naive

Naive solution would be to create a new List and add elements to it using a for-each loop as shown below:

 

Download   Run Code

Output:

[T, e, c, h, i, e, , D, e, l, i, g, h, t]

 

We can also use simple for loop as shown below:

 

Download   Run Code

Output:

[T, e, c, h, i, e, , D, e, l, i, g, h, t]

 

2. Java 8

We can call chars() method on a String in Java 8, which returns an IntStream. Then we convert IntStream to Stream of Character using a lambda expression, and collect the Stream to a new List using a Collector.

 

Download   Run Code

Output:

[T, e, c, h, i, e, , D, e, l, i, g, h, t]

 
We can also use IntStream.range() to directly access each character and add it to the list as shown below:

 

Download   Run Code

Output:

[T, e, c, h, i, e, , D, e, l, i, g, h, t]

 

3. AbstractList

To create a immutable List backed by the string, we can implement AbstractList Interface.

 

Download   Run Code

Output:

[T, e, c, h, i, e, , D, e, l, i, g, h, t]

 

4. Guava

Another plausible way of converting a String to a List of Character is using some third-party library. Guava’s Chars class provides several static utility methods pertaining to char primitives. One such method is asList() which returns a fixed-size list backed by the array of char primitives.

 

Download   Run Code

Output:

[T, e, c, h, i, e, , D, e, l, i, g, h, t]

 

We can also use Guava library Lists class which provides static utility methods pertaining to List instances. It has charactersOf() method that returns a view of the specified string as an immutable list of Character values.

 

Download   Run Code

Output:

[T, e, c, h, i, e, , D, e, l, i, g, h, t]

 

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of