Implementing Java Stream Gatherers: Integrators, State, Short-Circuiting and Parallelism
Write your own Java stream gatherers: the initializer, integrator, combiner and finisher, pushing elements downstream, Gatherer.of versus ofSequential, greedy versus short-circuiting integrators, finishers that flush state, and the rules for hand-written Gatherer classes.
kvi5hnuCode Sprout team member9 min readOn this page
The predefined gatherers from the previous article cover windows, folds and concurrent mapping. The real power of the Gatherer interface is that you can write your own intermediate operations: every nth element, "distinct by key", batches limited by size, "take until and including", and anything else a stream lacks. If you've implemented a collector (article 12), the structure will look familiar.
The four functions
Like a collector, a Gatherer<T, A, R> is made of up to four functions. T is the type of the incoming elements, A the type of the gatherer's private state, and R the type of the elements it produces.
| Method | Function type | Job |
|---|---|---|
initializer() | Supplier<A> | creates a new state object |
integrator() | Gatherer.Integrator<A, T, R> | processes one incoming element |
combiner() | BinaryOperator<A> | merges two states (parallel streams only) |
finisher() | BiConsumer<A, Downstream<? super R>> | runs after the last element, and may emit more elements |
The integrator is the heart of a gatherer. Gatherer.Integrator is a functional interface with one method:
boolean integrate(A state, T element, Gatherer.Downstream<? super R> downstream)
To send an element on to the next stage of the pipeline, call downstream.push(value). You can push once per element (like map), zero times (like filter), several times (like flatMap), or hold elements back in the state and push them later (like windowFixed). The boolean return value is explained under short-circuiting below.
Only the integrator is required. A stateless gatherer needs no initializer, a sequential one needs no combiner, and a finisher is needed only when there's something to push after the input ends. For example, windowFixed pushes the final, partial window in its finisher.
A first gatherer: every nth element
This gatherer keeps every nth element. Its state is a counter, wrapped in a small class because the integrator must update it:
static class Counter {
long index = -1;
}
static <T> Gatherer<T, Counter, T> everyNth(int n) {
return Gatherer.ofSequential(
Counter::new, // initializer
Gatherer.Integrator.ofGreedy((state, element, downstream) -> {
state.index++;
if (state.index % n == 0) return downstream.push(element);
return true;
}));
}
List<String> samples = words.stream().gather(everyNth(50)).toList();
Two choices are made here, and you make them for every gatherer.
Sequential or parallelizable?
Gatherer.ofSequential creates a gatherer that sees the elements one at a time, in encounter order, even if the stream is parallel. The stages before and after it can still run in parallel. Counting positions only makes sense sequentially, which is exactly what a collector couldn't promise (article 12).
Gatherer.of creates a parallelizable gatherer. In a parallel stream, each chunk gets its own state, and if the gatherer is stateful you must supply a combiner to merge states. Stateless gatherers parallelize trivially:
static <T, R> Gatherer<T, Void, R> mapNonNull(Function<? super T, ? extends R> mapper) {
return Gatherer.of(Gatherer.Integrator.ofGreedy((_, element, downstream) -> {
R result = mapper.apply(element);
return result == null || downstream.push(result);
}));
}
The state type of a stateless gatherer is Void, and the unused state parameter is written as _.
Greedy or short-circuiting?
The integrator returns true to say "keep sending me elements" and false to say "stop, I want no more". There are two reasons to return false:
- Your gatherer decides to stop.
takeUntilbelow stops after the first element that matches. - A later stage has stopped. If something downstream, such as
limitorfindFirst, needs no more elements,pushreturnsfalse. Your integrator must pass that on by returningfalsetoo. The usual idiom isreturn downstream.push(x);.
A gatherer whose integrator never stops on its own is greedy. Declaring that with Integrator.ofGreedy lets the stream optimize, for example by pushing elements in bulk. Use Integrator.of (or a plain lambda) when the integrator might short-circuit on its own:
static <T> Gatherer<T, Void, T> takeUntil(Predicate<? super T> stop) {
return Gatherer.ofSequential(Gatherer.Integrator.of((_, element, downstream) ->
downstream.push(element) && !stop.test(element)));
}
A plain lambda would also be converted to an Integrator, but writing Integrator.of tells readers clearly that it's not greedy. Because takeUntil short-circuits, it can end an infinite stream, as the demo shows.
State and finishers
A distinctBy gatherer keeps the first element for each key. Its state is the set of keys already seen:
static <T, K> Gatherer<T, ?, T> distinctBy(Function<? super T, ? extends K> key) {
return Gatherer.ofSequential(
() -> new HashSet<K>(),
Gatherer.Integrator.ofGreedy((seen, element, downstream) ->
!seen.add(key.apply(element)) || downstream.push(element)));
}
If the key was already seen, add returns false and the integrator returns true without pushing. Otherwise the element is pushed.
When a gatherer holds elements back, it needs a finisher to release whatever is left at the end. The demo's batchByLength(max) groups words into batches whose total length stays at most max characters. When the next word doesn't fit, the current batch is pushed. After the last word, the finisher pushes the incomplete final batch:
(batch, downstream) -> {
if (!batch.items.isEmpty()) downstream.push(List.copyOf(batch.items));
}
The batches are pushed as immutable copies so that later changes to the state's list can't affect lists already sent downstream. A finisher has no return value. If the downstream is no longer accepting elements, its pushes are simply ignored.
Rules and characteristics
Collectors announce their characteristics with an enum. Gatherers use the identity of their functions instead:
- A gatherer is sequential if its
combiner()returns the very object returned byGatherer.defaultCombiner(). Otherwise it's parallelizable. - It's stateless if its
initializer()returnsGatherer.defaultInitializer(). - It has no finisher if
finisher()returnsGatherer.defaultFinisher(). - It's greedy if its integrator implements
Gatherer.Integrator.Greedy.
The factory methods (of, ofSequential, Integrator.of, Integrator.ofGreedy) take care of all this, which is why you should prefer them. If you write a class implementing Gatherer yourself, be careful. A sequential gatherer must not override combiner(). Keeping the default method is what marks it as sequential. A parallelizable gatherer must override combiner() even if merging is trivial.
Here's a checklist for writing a gatherer:
- Can it run on chunks independently (
Gatherer.of, with a combiner if stateful), or must it see elements in order (Gatherer.ofSequential)? - Can it stop on its own (
Integrator.of), or does it always accept elements (Integrator.ofGreedy)? - Does it need state? Give it a state class and an initializer that creates a fresh state each time. Never share state between pipelines.
- Return
falsewhen stopping, and always return the result ofpushwhen you push. - Does it hold elements back? Push them in the finisher.
A complete example
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Solution {
// 1. stateful, sequential, greedy: every nth element
static class Counter {
long index = -1;
}
static <T> Gatherer<T, Counter, T> everyNth(int n) {
return Gatherer.ofSequential(
Counter::new,
Gatherer.Integrator.ofGreedy((state, element, downstream) -> {
state.index++;
if (state.index % n == 0) return downstream.push(element);
return true;
}));
}
// 2. stateless and parallelizable: map, dropping null results
static <T, R> Gatherer<T, Void, R> mapNonNull(Function<? super T, ? extends R> mapper) {
return Gatherer.of(Gatherer.Integrator.ofGreedy((_, element, downstream) -> {
R result = mapper.apply(element);
return result == null || downstream.push(result);
}));
}
// 3. short-circuiting on its own: take elements up to and including the first match
static <T> Gatherer<T, Void, T> takeUntil(Predicate<? super T> stop) {
return Gatherer.ofSequential(Gatherer.Integrator.of((_, element, downstream) ->
downstream.push(element) && !stop.test(element)));
}
// 4. stateful: keep only the first element for each key
static <T, K> Gatherer<T, ?, T> distinctBy(Function<? super T, ? extends K> key) {
return Gatherer.ofSequential(
() -> new HashSet<K>(),
Gatherer.Integrator.ofGreedy((seen, element, downstream) ->
!seen.add(key.apply(element)) || downstream.push(element)));
}
// 5. batches whose total weight stays under a limit; the finisher pushes the last batch
static Gatherer<String, ?, List<String>> batchByLength(int maxChars) {
class Batch {
List<String> items = new ArrayList<>();
int chars;
}
return Gatherer.ofSequential(
Batch::new,
Gatherer.Integrator.ofGreedy((batch, word, downstream) -> {
if (!batch.items.isEmpty() && batch.chars + word.length() > maxChars) {
List<String> full = List.copyOf(batch.items);
batch.items.clear();
batch.chars = 0;
if (!downstream.push(full)) return false;
}
batch.items.add(word);
batch.chars += word.length();
return true;
}),
(batch, downstream) -> {
if (!batch.items.isEmpty()) downstream.push(List.copyOf(batch.items));
});
}
public static void main(String[] args) {
List<Integer> numbers = IntStream.rangeClosed(1, 20).boxed().toList();
System.out.println("everyNth(5): " + numbers.stream().gather(everyNth(5)).toList());
System.out.println("everyNth(5), parallel: " + numbers.parallelStream().gather(everyNth(5)).toList());
Map<String, Integer> stock = Map.of("apple", 3, "pear", 0, "plum", 7);
System.out.println("mapNonNull: " + Stream.of("apple", "kiwi", "plum", "fig")
.gather(mapNonNull(stock::get)).toList());
System.out.println("mapNonNull, parallel: " + numbers.parallelStream()
.gather(mapNonNull(n -> n % 3 == 0 ? n * n : null)).toList());
System.out.println("takeUntil: " + Stream.of(3, 8, 12, 5, 20).gather(takeUntil(n -> n > 10)).toList());
var seen = new ArrayList<Integer>();
Stream.iterate(1, n -> n + 1).peek(seen::add).gather(takeUntil(n -> n * n > 30)).toList();
System.out.println("takeUntil stops an infinite stream after " + seen.size() + " elements");
System.out.println("distinctBy length: " + Stream.of("one", "two", "three", "four", "five", "six", "seven")
.gather(distinctBy(String::length)).toList());
List<String> words = List.of("gatherers", "are", "intermediate", "operations", "for", "streams", "in", "Java");
System.out.println("batches of at most 15 chars: " + words.stream().gather(batchByLength(15)).toList());
System.out.println("first batch only: " + words.stream().gather(batchByLength(15)).findFirst().orElseThrow());
// composing custom and predefined gatherers
System.out.println("andThen: " + numbers.stream()
.gather(everyNth(3).andThen(Gatherers.windowFixed(2))).toList());
// a hand-written gatherer class must leave combiner() alone to stay sequential
Gatherer<Integer, Void, Integer> doubler = new Gatherer<>() {
@Override
public Integrator<Void, Integer, Integer> integrator() {
return Integrator.ofGreedy((_, n, downstream) -> downstream.push(n) && downstream.push(n));
}
};
System.out.println("pushing twice: " + Stream.of(1, 2, 3).gather(doubler).toList());
System.out.println("doubler is sequential: " + (doubler.combiner() == Gatherer.<Void>defaultCombiner()));
}
}
everyNth(5): [1, 6, 11, 16]
everyNth(5), parallel: [1, 6, 11, 16]
mapNonNull: [3, 7]
mapNonNull, parallel: [9, 36, 81, 144, 225, 324]
takeUntil: [3, 8, 12]
takeUntil stops an infinite stream after 6 elements
distinctBy length: [one, three, four]
batches of at most 15 chars: [[gatherers, are], [intermediate], [operations, for], [streams, in, Java]]
first batch only: [gatherers, are]
andThen: [[1, 4], [7, 10], [13, 16], [19]]
pushing twice: [1, 1, 2, 2, 3, 3]
doubler is sequential: true
everyNth gives the same answer on a parallel stream because it's sequential. Only its own stage runs one element at a time. The custom gatherers also compose with andThen and with the predefined ones.
Common questions
How do I number the elements, a "zip with index"?
A sequential gatherer with a counter does it: Gatherer.ofSequential(() -> new long[1], Gatherer.Integrator.ofGreedy((count, element, downstream) -> downstream.push(new Indexed<>(count[0]++, element)))), where Indexed is a small record. Before gatherers, the usual workaround was IntStream.range(0, list.size()).mapToObj(i -> new Indexed<>(i, list.get(i))), which works only for indexable sources.
Can I keep the state in a variable captured by the lambda instead of an initializer?
Do not. A captured AtomicInteger or list is shared by every pipeline that uses the gatherer, and by every chunk of a parallel stream, so a second use starts with leftover state. The initializer runs once per evaluation, giving each one fresh state.
When do I need a gatherer, and when is mapMulti enough?
mapMulti handles any stateless "one element in, zero or more out" step. You need a gatherer when the step has state (it remembers earlier elements), needs to stop early on its own, or must flush something at the end.
Can I use gatherers on Java 21, the previous LTS?
No. Gatherers are final only since Java 24, so on Java 21 write a custom Spliterator, collect to a list first, or use a library. Java 25 is the current LTS and includes them.
How do I debug a gatherer?
Test it on small lists with Stream.of(...).gather(g).toList(), including an empty stream, a stream that ends mid-batch, and a stream that is cut short with limit. Then run it on a parallel stream to make sure the result does not change.
API reference
java.util.stream.Gatherer<T, A, R> (Java 24)
| Method | Description |
|---|---|
Supplier<A> initializer() | creates the state; default: stateless |
Gatherer.Integrator<A, T, R> integrator() | processes each element |
BinaryOperator<A> combiner() | merges states; default: the gatherer is sequential |
BiConsumer<A, Gatherer.Downstream<? super R>> finisher() | runs after the last element; default: does nothing |
static ofSequential(integrator), ofSequential(integrator, finisher), ofSequential(initializer, integrator), ofSequential(initializer, integrator, finisher) | sequential gatherers |
static of(integrator), of(integrator, finisher), of(initializer, integrator, combiner, finisher) | parallelizable gatherers |
static defaultInitializer(), defaultCombiner(), defaultFinisher() | the marker objects described above |
java.util.stream.Gatherer.Integrator<A, T, R>
| Method | Description |
|---|---|
boolean integrate(A state, T element, Gatherer.Downstream<? super R> downstream) | processes one element; returns false to stop |
static Integrator<A, T, R> of(Integrator<A, T, R> integrator) | marks an integrator that may short-circuit |
static Integrator.Greedy<A, T, R> ofGreedy(Integrator.Greedy<A, T, R> greedy) | marks an integrator that never stops on its own |
java.util.stream.Gatherer.Downstream<T>
| Method | Description |
|---|---|
boolean push(T element) | sends an element to the next stage; returns false if no more are wanted |
boolean isRejecting() | whether further pushes will be ignored |
Summary
- A gatherer has an initializer (state), an integrator (per element), a combiner (parallel only) and a finisher (after the last element). Only the integrator is required.
- The integrator emits elements with
downstream.push, any number of times per input element. Gatherer.ofSequentialprocesses elements in order.Gatherer.ofis parallelizable and needs a combiner when stateful.- Return
falsefrom the integrator to stop, and pass on the result ofpush. UseIntegrator.ofGreedywhen the integrator never stops on its own. - Use the finisher to flush held-back elements. Prefer the factory methods over hand-written
Gathererclasses.
Practice Questions
Your integrator does downstream.push(x); return true;. What's wrong?
It ignores the result of push. If a later stage such as limit(3) or findFirst() no longer wants elements, push returns false, and the integrator should return false so the stream can stop. Write return downstream.push(x);.
Why is everyNth built with ofSequential and not of?
It depends on each element's position in the whole stream. In a parallel stream, a gatherer made with of would process each chunk with its own counter starting at zero, selecting the wrong elements. ofSequential guarantees in-order processing with a single state.
Write a stateless gatherer that pushes each string followed by its length, both as Objects.
Gatherer.<String, Object>of(Gatherer.Integrator.ofGreedy((_, s, downstream) -> downstream.push(s) && downstream.push(s.length()))). Each input produces two outputs, and the result of the pushes is passed on.
A gatherer groups elements into pairs. Without a finisher, what happens to the last element of an odd-length stream?
It stays in the state and is lost, because nothing pushes it after the input ends. A finisher must check the state and push the incomplete pair (or decide deliberately to drop it).
You write a class implementing Gatherer and override combiner() to return (a, b) -> a. What changes?
The gatherer is now considered parallelizable, because its combiner is no longer Gatherer.defaultCombiner(). A parallel stream will process chunks with separate states and "merge" them by discarding one, which is almost certainly wrong. For a sequential gatherer, don't override combiner().
Previous: Java Stream Gatherers: windowFixed, windowSliding, fold, scan and mapConcurrent
Next: Java Primitive Streams: IntStream, LongStream and DoubleStream
Related reading
- Java Stream Gatherers: windowFixed, windowSliding, fold, scan and mapConcurrent
- Java Stream reduce: Identity, Accumulator, Combiner and Three-Argument collect
- Implementing Custom Java Collectors with Collector.of
- Java Downstream Collectors: counting, mapping, filtering, teeing and More
- Java groupingBy and partitioningBy: Grouping Stream Elements

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.