Java Reference
In-Depth Information
Figure 7.7. The state transitions of the WordCounter when a new
Character c is traversed
The second method, combine, is invoked to aggregate the partial results of two WordCounters
operating on two different subparts of the stream of Characters, so it combines two
WordCounters by summing their internal counters.
Now that you've encoded the logic of how to accumulate characters on a WordCounter and how
to combine them in the WordCounter itself, writing a method that will reduce the stream of
Characters is straightforward:
private int countWords(Stream<Character> stream) {
WordCounter wordCounter = stream.reduce(new WordCounter(0, true),
WordCounter::accumulate,
WordCounter::combine);
return wordCounter.getCounter();
}
Now you can try this method with the stream created from the String containing the first
sentence of Dante's Inferno :
Stream<Character> stream = IntStream.range(0, SENTENCE.length())
.mapToObj(SENTENCE::charAt);
System.out.println("Found " + countWords(stream) + " words");
You can check that its output corresponds with the one generated by the iterative version:
Found 19 words
 
Search WWH ::




Custom Search