Java Reference
In-Depth Information
.mapToObj(SENTENCE::charAt);
You can calculate the number of words by performing a reduction on this stream. While
reducing the stream, you'll have to carry a state consisting of two variables: an int counting the
number of words found so far and a boolean to remember if the last-encountered Character was
a space or not. Because Java doesn't have tuples (a construct to represent an ordered list of
heterogeneous elements without the need of a wrapper object), you'll have to create a new class,
WordCounter, which will encapsulate this state as shown in the following listing.
Listing 7.5. A class to count words while traversing a stream of
Characters
In this listing, the accumulate method defines how to change the state of the WordCounter, or
more precisely with which state to create a new WordCounter because it's an immutable class.
The method accumulate is called whenever a new Character of the Stream is traversed. In
particular, as you did in the countWordsIteratively method in listing 7.4 , the counter is
incremented when a new nonspace is met and the last character encountered is a space. Figure
7.7 shows the state transitions of the WordCounter when a new Character is traversed by the
accumulate method.
 
Search WWH ::




Custom Search