Chaining many operations with map and reduce
We can chain filter, map, and reduce operations. The following code adds a new getHighestScoreSumForMinPlayersCount method to the MemoryMobileGameRepository class. The code file for the sample is included in the java_9_oop_chapter_12_01 folder, in the example12_19.java file.
public long getHighestScoreSumForMinPlayersCount(int minPlayersCount) {
return getAll().stream()
.filter(game -> (game.playersCount >= minPlayersCount))
.mapToLong(game -> game.highestScore)
.reduce(0, (sum, highestScore) -> sum + highestScore);
}The new method performs a filter chained with a mapToLong and finally a reduce operation. The call to filter generates a Stream<MobileGame> with the instance of MobileGame whose playersCount value is equal or greater than the minPlayersCount value received as an argument. The mapToLong method returns a LongStream, that is, a specialized Stream<T> that describes a stream of long primitives...