Java Reference
In-Depth Information
Listing 6.4. The Collector interface
public interface Collector<T, A, R> {
Supplier<A> supplier();
BiConsumer<A, T> accumulator();
Function<A, R> finisher();
BinaryOperator<A> combiner();
Set<Characteristics> characteristics();
}
In this listing, the following definitions apply:
T is the generic type of the items in the stream to be collected.
A is the type of the accumulator, the object on which the partial result will be accumulated during the
collection process.
R is the type of the object (typically, but not always, the collection) resulting from the collect
operation.
For instance, you could implement a ToListCollector<T> class that gathers all the elements of a
Stream<T> into a List<T> having the following signature
public class ToListCollector<T> implements Collector<T, List<T>, List<T>>
where, as we'll clarify shortly, the object used for the accumulation process will also be the final
result of the collection process.
6.5.1. Making sense of the methods declared by Collector interface
We can now analyze one by one the five methods declared by the Collector interface. When we
do so, you'll notice that each of the first four methods returns a function that will be invoked by
the collect method, whereas the fifth one, characteristics, provides a set of characteristics that's
a list of hints used by the collect method itself to know which optimizations (for example,
parallelization) it's allowed to employ while performing the reduction operation.
Making a new result container: the supplier method
The supplier method has to return a Supplier of an empty result—a parameterless function that
when invoked creates an instance of an empty accumulator used during the collection process.
Clearly, for a collector returning the accumulator itself as result, like our ToListCollector, this
 
Search WWH ::




Custom Search