Java Reference
In-Depth Information
Factory
method
Returned type
Used to
Example
use:
Map<Dish.Type,
List<Dish>>
dishesByType
=
menuStream.collect(groupingBy(Dish::getType));
partitioningBy
Map<Boolean, List<T>>
Partition the items in the stream based on the result of
the application of a predicate to each of them.
Example
use:
Map<Boolean,
List<Dish>>
vegetarianDishes
=
menuStream.collect(partitioningBy(Dish::isVegetarian));
As we mentioned at the beginning of the chapter, all these collectors implement the Collector
interface, so in the remaining part of the chapter we investigate this interface in more detail. We
investigate the methods in that interface and then explore how you can implement your own
collectors.
6.5. The Collector interface
The Collector interface consists of a set of methods that provide a blueprint for how to
implement specific reduction operations (that is, collectors). You've seen many collectors that
implement the Collector interface, such as toList or groupingBy. This also implies that you're
free to create customized reduction operations by providing your own implementation of the
Collector interface. In section 6.6 we show how you can implement the Collector interface to
create a collector to partition a stream of numbers into prime and nonprime more efficiently
than what you've seen so far.
To get started with the Collector interface, we focus on one of the first collectors you
encountered at the beginning of this chapter: the toList factory method, which gathers all the
elements of a stream in a List. We said that you'll frequently use this collector in your day-to-day
job, but it's also one that, at least conceptually, is straightforward to develop. Investigating in
more detail how this collector is implemented is a good way to understand how the Collector
interface is defined and how the functions returned by its methods are internally used by the
collect method.
Let's start by taking a look at the definition of the Collector interface in the next listing, which
shows the interface signature together with the five methods it declares.
 
Search WWH ::




Custom Search