How to convert a String to Java 8 Stream of Char?

We can convert a String to a stream of characters using the chars() method from the CharSequence interface and then convert it to a Stream<Character> using the mapToObj() intermediate operation.


Example:
String str = "Welcome to Code2care.org";
Stream<Character> charStream = str.chars().mapToObj(c -> (char) c);
charStream.forEach(System.out::println);
Output:
W
e
l
c
o
m
e
 
t
o
 
C
o
d
e
2
c
a
r
e
.
o
r
g

Reference:

https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#chars--

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!