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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap