Java 8 introduced the Stream API, with functional-like operations for processing sequences. If you want to read more about it, have a look at this article.
In this quick article, we’ll see how to convert a String
to a Stream
of single characters.
The String
API has a new method – chars()
– with which we can obtain an instance of Stream
from a String object. This simple API returns an instance of IntStream from the input String.
Simply put, IntStream
contains an integer representation of the characters from the String
object:
String testString = "String";
IntStream intStream = testString.chars();
It’s possible to work with the integer representation of the characters without converting them to their Character
equivalent. This can lead to some minor performance gains, as there will be no need to box each integer into a Character
object.
However, if we’re to display the characters for reading, we need to convert the integers to the human-friendly Character
form:
Stream<Character> characterStream = testString.chars()
.mapToObj(c -> (char) c);
Alternatively, we can use the codePoints()
method to get an instance of IntStream
from a String
. The advantage of using this API is that Unicode supplementary characters can be handled effectively.
Supplementary characters are represented by Unicode surrogate pairs and will be merged into a single codepoint. This way we can correctly process (and display) any Unicode symbol:
IntStream intStream1 = testString.codePoints();
We need to map the returned IntStream
to Stream<Character>
to display it to users:
Stream<Character> characterStream2
= testString.codePoints().mapToObj(c -> (char) c);
So far, we’ve been able to get a Stream
of characters; what if we want a Stream of single character Strings
instead?
Just as specified earlier in the article, we’ll use either the codePoints()
or chars()
methods to obtain an instance of IntStream that we can now map to Stream<String>
.
The mapping process involves converting the integer values to their respective character equivalents first.
Then we can use String.valueOf() or Character.toString() to convert the characters to a String object:
Stream<String> stringStream = testString.codePoints()
.mapToObj(c -> String.valueOf((char) c));
In this quick tutorial, we learn to obtain a stream of Character from a String object by either calling codePoints()
or chars()
methods.
This allows us to take full advantage of the Stream API
– to conveniently and effectively manipulate characters.
As always, code snippets can be found over on GitHub.