The gatherer defines how elements flowing through a stream should be processed. It can maintain mutable state, optionally combine partial states during parallel processing, and push zero, one, or multiple elements downstream.
Simple Code Sample
The following code sample demonstrates a gatherer that calculates the total of all elements and prints it to the screen.
class MutableInt {
int value = 0;
public void add(int i) {
value += i;
}
}
public class CustomGathererDemo {
static void main() {
Stream strm =
IntStream.range(0, 10)
.boxed()
.parallel();
Object result =
strm.gather(
Gatherer.of(
MutableInt::new,
(state, element, downstream) -> {
state.value += element;
return true;
},
(state1, state2) -> {
state1.value += state2.value;
return state1;
},
(state, downstream) -> {
downstream.push(state.value);
}
)
).findFirst();
System.out.println(result);
}
}
When executing this code sample we will get the following output.
Optional[45]
The Four Parts of a Custom Gatherer
We can easily understand how a custom gatherer works by identifying its four parts, and the purpose of each one of them.
Initializer
The first argument creates the state of our gatherer.
MutableInt::new
When the stream runs in parallel, different partitions may receive separate state objects. This way, when having multiple threads they won’t manipulate the same accumulator. Each thread will have its specific accumulator.
Integrator
The second argument is responsible to process each incoming stream element.
(state, element, downstream) -> {
state.value += element;
return true;
}
The state is the mutable state created by the initializer. The element is the current stream element. The downstream object can be used to emit elements into the resulting stream. For this particular gatherer, we do not emit anything immediately. We simply accumulate the value. The returned boolean controls whether processing should continue:
Combinar
The third argument becomes especially important when using parallel streams. Each partition of a parallel stream may calculate its own partial result.
(state1, state2) -> {
state1.value += state2.value;
return state1;
}
The combiner merges these states. Without an appropriate combiner, the stateful gatherer won’t work for parallel execution.
Finisher
The final argument is called when processing is complete. Until this point, the gatherer has only accumulated the data internally. The finisher sends the final result downstream:
(state, downstream) -> {
downstream.push(state.value);
}
Using a custom gatherer, we are not limited to the predefined intermediate operations; we can define our own stateful transformations while still using the Stream API pipeline.







