Java Reference
In-Depth Information
else if (this.getCalories() <= 700) return CaloricLevel.NORMAL;
else return CaloricLevel.FAT;
}
}
In addition, consider making use of helper static methods such as comparing and maxBy when
possible. These methods were designed for use with method references! Indeed, this code states
much more clearly its intent than its counterpart using a lambda expression, as we showed in
chapter 3 :
Moreover, for many common reduction operations such as sum , maximum there are built-in
helper methods that can be combined with method references. For example, we showed that
using the Collectors API you can find the maximum or sum in a clearer way than using a
combination of a lambda expression and a lower-level reduce operation. Instead of writing
int totalCalories =
menu.stream().map(Dish::getCalories)
.reduce(0, (c1, c2) -> c1 + c2);
try using alternative built-in collectors, which state more clearly what the problem statement is.
Here we use the collector summingInt (names go a long way in documenting your code):
int totalCalories = menu.stream().collect(summingInt(Dish::getCalories));
8.1.4. From imperative data processing to Streams
Ideally, you should try to convert all code that processes a collection with typical data processing
patterns with an iterator to use the Streams API instead. Why? The Streams API expresses more
clearly the intent of a data processing pipeline. In addition, streams can be optimized behind the
scenes making use of short-circuiting and laziness, as well as leveraging your multicore
architecture, as we explained in chapter 7 .
For example, the following imperative code expresses two patterns (filtering and extracting) that
are mangled together, which forces the programmer to carefully understand the whole
implementation before figuring out what the code does. In addition, an implementation that
 
Search WWH ::




Custom Search