Java Reference
In-Depth Information
}
Use of the generic ? wildcard
In the code snippet just shown, you probably noticed the ? wildcard, used as the second generic
type in the signature of the collector returned by the counting factory method. You should
already be familiar with this notation, especially if you use the Java Collection Framework quite
frequently. But here it means only that the type of the collector's accumulator is unknown, or in
other words, the accumulator itself can be of any type. We used it here to exactly report the
signature of the method as originally defined in the Collectors class, but in the rest of the
chapter we avoid any wildcard notation to keep the discussion as simple as possible.
We already observed in chapter 5 that there's another way to perform the same operation
without using a collector—by mapping the stream of dishes into the number of calories of each
dish and then reducing this resulting stream with the same method reference used in the
previous version:
int totalCalories =
menu.stream().map(Dish::getCalories).reduce(Integer::sum).get();
Note that, like any one-argument reduce operation on a stream, the invocation
reduce(Integer::sum) doesn't return an int but an Optional<Integer> to manage in a null-safe
way the case of a reduction operation over an empty stream. Here you just extract the value
inside the Optional object using its get method. Note that in this case using the get method is
safe only because you're sure that the stream of dishes isn't empty. In general, as you'll learn in
chapter 10 , it's safer to unwrap the value eventually contained in an Optional using a method
that also allows you to provide a default, such as orElse or orElseGet. Finally, and even more
concisely, you can achieve the same result by mapping the stream to an IntStream and then
invoking the sum method on it:
int totalCalories = menu.stream().mapToInt(Dish::getCalories).sum();
Choosing the best solution for your situation
Once again, this demonstrates how functional programming in general (and the new API based
on functional-style principles added to the Collections framework in Java 8 in particular) often
provides multiple ways to perform the same operation. This example also shows that collectors
Search WWH ::




Custom Search