Java Reference
In-Depth Information
1 . This converts each dish in its name, as done by the original statement using the joining
collector, and then reduces the resulting stream of strings using a String as accumulator and
appending to it the names of the dishes one by one.
2 . This doesn't compile because the one argument that reducing accepts is a
BinaryOperator<T> that's a BiFunction<T,T,T>. This means that it wants a function taking two
arguments and returns a value of the same type, but the lambda expression used there has two
dishes as arguments but returns a string.
3 . This starts the reduction process with an empty string as the accumulator, and when
traversing the stream of dishes it converts each dish to its name and appends this name to the
accumulator. Note that, as we mentioned, reducing doesn't need the three arguments to return
an Optional because in the case of an empty stream it can return a more meaningful value,
which is the empty string used as the initial accumulator value.
Note that even though statements 1 and 3 are valid replacements for the joining collector,
they've been used here to demonstrate how the reducing one can be seen, at least conceptually,
as a generalization of all other collectors discussed in this chapter. Nevertheless, for all practical
purposes we always suggest using the joining collector for both readability and performance
reasons.
6.3. Grouping
A common database operation is to group items in a set, based on one or more properties. As
you saw in the earlier transactions-currency-grouping example, this operation can be
cumbersome, verbose, and error prone when implemented with an imperative style. But it can
be easily translated in a single, very readable statement by rewriting it in a more functional style
as encouraged by Java 8. As a second example of how this feature works, suppose you want to
classify the dishes in the menu according to their type, putting the ones containing meat in a
group, the ones with fish in another group, and all others in a third group. You can easily
perform this task using a collector returned by the Collectors.groupingBy factory method as
follows:
Map<Dish.Type, List<Dish>> dishesByType =
menu.stream().collect(groupingBy(Dish::getType));
This will result in the following Map:
Search WWH ::




Custom Search