Java Reference
In-Depth Information
empty accumulator will also represent the result of the collection process when performed on an
empty stream. In our ToListCollector the supplier will then return an empty List as follows:
public Supplier<List<T>> supplier() {
return () -> new ArrayList<T>();
}
Note that you could also just pass a constructor reference:
public Supplier<List<T>> supplier() {
return ArrayList::new;
}
Adding an element to a result container: the accumulator method
The accumulator method returns the function that performs the reduction operation. When
traversing the n th element in the stream, this function is applied with two arguments, the
accumulator being the result of the reduction (after having collected the first n -1 items of the
stream) and the n th element itself. The function returns void because the accumulator is
modified in place, meaning that its internal state is changed by the function application to
reflect the effect of the traversed element. For ToListCollector, this function merely has to add
the current item to the list containing the already traversed ones:
public BiConsumer<List<T>, T> accumulator() {
return (list, item) -> list.add(item);
You could instead use a method reference, which is more concise:
public BiConsumer<List<T>, T> accumulator() {
return List::add;
}
Applying the final transformation to the result container: the finisher
method
The finisher method has to return a function that's invoked at the end of the accumulation
process, after having completely traversed the stream, in order to transform the accumulator
object into the final result of the whole collection operation. Often, as in the case of the
ToListCollector, the accumulator object already coincides with the final expected result. As a
 
Search WWH ::




Custom Search