Convert string to stream

Just the opposite of converting a java 8 stream into a string, this example will show how to convert a string to a Stream. A common use case may be where you want to filter a character or count the number of occurrences of a letter.

Java 8

The Strings.chars() will return an IntStream that will represent char values. With the Stream.forEach we will iterate over each element in the stream and pass in a lambda expression. The expression will print each character as a string by calling the Character.toString.

@Test
public void string_to_stream() {
    String val = "Levelup Lunch";

    val.chars().forEach(
            e -> System.out.println(Character.toString((char) e)));
}

Output

L
e
v
e
l
u
p
 
L
u
n
c
h