Java Reference
In-Depth Information
are somewhat more complex to use than the methods directly available on the Streams interface,
but in exchange they offer higher levels of abstraction and generalization and are more reusable
and customizable.
Our suggestion is to explore the largest number of solutions possible for the problem at hand,
but always choose the most specialized one that's general enough to solve it. This is often the
best decision for both readability and performance reasons. For instance, to calculate the total
calories in our menu, we'd prefer the last solution (using IntStream) because it's the most
concise and likely also the most readable one. At the same time, it's also the one that performs
best, because IntStream lets us avoid all the auto-unboxing operations, or implicit conversions
from Integer to int, that are useless in this case.
Next, take the time to test your understanding of how reducing can be used as a generalization
of other collectors by working through the exercise in Quiz 6.1 .
Quiz 6.1: Joining strings with reducing
Which of the following statements using the reducing collector are valid replacements for this
joining collector (as used in section 6.2.3 )?
String shortMenu = menu.stream().map(Dish::getName).collect(joining());
1 .
String shortMenu = menu.stream().map(Dish::getName)
.collect( reducing( (s1, s2) -> s1 + s2 ) ).get();
2 .
String shortMenu = menu.stream()
.collect( reducing( (d1, d2) -> d1.getName() + d2.getName() ) ).get();
3 .
String shortMenu = menu.stream()
.collect( reducing( "", Dish::getName, (s1, s2) -> s1 + s2 ) );
Answer:
Statements 1 and 3 are valid, whereas 2 doesn't compile.
Search WWH ::




Custom Search