Quiz: Stream Gatherers in Java: the gather() Method
Study the lesson first: Stream Gatherers in Java: the gather() Method
Total: 7 questions
1. What are Stream Gatherers and the gather() method in Java, and since which version are they available?
What are Stream Gatherers and the gather() method in Java, and since which version are they available?
Stream Gatherers are the mechanism for writing your own intermediate operations in the Stream API. Stream.gather(Gatherer) is an intermediate operation that lets you write a custom intermediate operation the same way collect(Collector) lets you write a custom terminal one. A Gatherer can keep state between elements, turn one input element into zero, one or many output elements, stop the stream early and, if it has a combiner, run in a parallel stream.
Why it exists: the set of built-in intermediate operations (filter(), map(), distinct(), limit()...) is fixed, and tasks such as batches of 1000 records, a sliding window, a running total, distinct by key or "take until the sum exceeds a limit" used to be solved with indexes, collect() followed by a new stream, or a plain loop. For example, orders.stream().gather(Gatherers.windowFixed(3)) works with any stream, including Files.lines() and an infinite Stream.iterate(), and stays lazy.
Versions: the final API is in Java 24 (JEP 485), with previews in Java 22 (JEP 461) and Java 23 (JEP 473) behind --enable-preview. Java 25 is the first LTS release with gatherers; Java 21 does not have them. The ready-made implementations live in java.util.stream.Gatherers.
2. How does a Gatherer differ from a Collector, and gather() from collect()?
How does a Gatherer differ from a Collector, and gather() from collect()?
A Collector folds the whole stream into one value and ends the pipeline, while a Gatherer turns a stream into another stream and keeps the pipeline open: after gather() you can call map(), filter() and another gather(), after collect() you cannot.
- Operation type:
gather()is intermediate,collect()is terminal. - Emitting as it goes: a gatherer integrator can send an element downstream right away with
downstream.push(); a collector accumulator only adds elements to a container, and the result appears at the end. - Input and output: a gatherer maps 1 → 0..N, N → 1, N → M; a collector maps all elements → one value.
- Early termination: the integrator returns
false, so a gatherer works on an infinite stream too; a collector reads the whole stream. - State: optional for a gatherer (without an initializer it is stateless); a collector always has a container from the supplier.
- Parallelism: a gatherer runs in parallel only if it has a combiner; a collector always gets a combiner.
- Four functions: initializer, integrator, combiner, finisher versus supplier, accumulator, combiner, finisher. Factories:
Gatherer.of()/ofSequential()versusCollector.of().
When you need a final object (a collection, a Map, a number), use a collector; when the result is again a stream of elements, use a gatherer. They can be chained: stream.gather(...).collect(...).
3. Which ready-made gatherers does the Gatherers class provide, and what are their edge cases?
Which ready-made gatherers does the Gatherers class provide, and what are their edge cases?
java.util.stream.Gatherers (Java 24+) has five methods:
windowFixed(n)- non-overlapping windows ofnelements: for1..5andn = 2→[1, 2], [3, 4], [5]. The last window may be shorter; an empty stream produces no windows.windowSliding(n)- a sliding window that moves by one element:[1, 2], [2, 3], [3, 4], [4, 5]. If the stream is shorter than the window, you get one incomplete window with all the elements.fold(initial, folder)- folds into one value, but as an intermediate operation: the result is a one-element stream. On an empty stream it emits the initial value. The result type can differ from the element type, and unlike the three-argumentreduce()no combiner is needed.scan(initial, scanner)- a running total:1, 3, 6, 10, 15. The initial value is not emitted; an empty stream gives an empty stream.mapConcurrent(max, mapper)-mapon virtual threads, at mostmaxtasks at a time, results in the original order. Meant for functions that mostly wait (HTTP, database); an exception from the function is rethrown and the remaining tasks are cancelled.
Windows are unmodifiable Lists (changing one → UnsupportedOperationException; copy with new ArrayList<>(window)). windowFixed(0), windowSliding(0) and mapConcurrent(0, ...) throw IllegalArgumentException right at the call, before the stream starts. All five are created with Gatherer.ofSequential().
4. What four functions make up a Gatherer, and what do Downstream.push() and isRejecting() do?
What four functions make up a Gatherer, and what do Downstream.push() and isRejecting() do?
The Gatherer<T, A, R> interface (T - input element type, A - state type, R - output element type) is described by four functions; only the integrator is mandatory.
- initializer (
Supplier<A>) - creates the state, once per stream run (once per segment in a parallel stream). Without it the gatherer is stateless. - integrator (
Integrator<A, T, R>) - called for every element, returns aboolean:falsemeans "no more elements needed". - combiner (
BinaryOperator<A>) - merges the states of two segments of a parallel stream. Without it the gatherer runs only sequentially. - finisher (
BiConsumer<A, Downstream<? super R>>) - called once after the input ends or after the integrator returnedfalse; it sends whatever is left in the state (an incomplete batch, a total).
Instead of returning a result, the integrator and the finisher receive a Gatherer.Downstream - the next stage of the pipeline. downstream.push(element) sends an element on and returns false when the next stage will accept nothing more (for example, it is followed by limit() or findFirst()); after that every later push() returns false too. isRejecting() lets you check this in advance without sending an element, but it is best-effort: false does not guarantee the element will be accepted.
Hence the rule: if there is no need to continue, return false; if an element was pushed, return the result of push(). Then the "enough" signal reaches the source.
5. How do you write a custom gatherer: what is the difference between Gatherer.of() and ofSequential(), and between Integrator.of() and ofGreedy()?
How do you write a custom gatherer: what is the difference between Gatherer.of() and ofSequential(), and between Integrator.of() and ofGreedy()?
A gatherer is usually not implemented as a class but assembled with static factories and returned from a static method, the way Gatherers and Collectors do it.
Gatherer.of(integrator),of(integrator, finisher)- stateless and parallelizable (your ownmap,filter).Gatherer.of(initializer, integrator, combiner, finisher)- stateful and parallel: an aggregate that can merge partial results.Gatherer.ofSequential(...)- with or without state, sequential only: batches, distinct by key, a sum limit - anything where strict order matters or the state is not thread-safe (HashSet).
Integrator.ofGreedy() creates a greedy integrator: it processes all elements and never stops the stream on its own, only passes on a rejection from the next stage (return downstream.push(...)). It is an optimisation hint. Integrator.of() promises nothing and is needed when the integrator returns false by its own logic, as in "take until the sum exceeds a limit". When in doubt, use of(): it is always correct.
Two more rules: mutable state is created only in the initializer (() -> new HashSet<K>()), and if unsent data may remain in the state at the end, you need a finisher. Argument checks (such as the batch size) go before the gatherer is created, so the error happens at the call rather than while the stream runs.
6. How do gatherers behave in parallel streams, and how do you combine two gatherers into one?
How do gatherers behave in parallel streams, and how do you combine two gatherers into one?
A gatherer without a combiner (created with ofSequential()) does not break in a parallelStream(): its stage runs sequentially, keeps the order and gives the correct result. For the stage to run in parallel it needs a combiner - Gatherer.of(initializer, integrator, combiner, finisher): each segment of the input gets its own state, the combiner merges them, and the finisher runs once on the merged state. The combiner must give the same result as sequential processing: true for a sum, false for "the first element per key". All five built-in gatherers are sequential: windows and running totals depend on order.
Thread safety: the integrator is never called concurrently on the same state object, so state from the initializer can use plain ArrayList, HashSet and arrays. What is unsafe is anything the lambdas capture from outside: a shared collection, a counter, a class field.
Composition: a.andThen(b) feeds the output of a into b and gives the same result as .gather(a).gather(b), but the composed gatherer is an ordinary object you can store in a constant and reuse. For example, Gatherers.scan(() -> 0, Integer::sum).andThen(Gatherers.windowFixed(2)) on 1..5 gives [[1, 3], [6, 10], [15]]. A composed gatherer is parallelizable only if both parts are.
7. What are the most common mistakes when working with gatherers?
What are the most common mistakes when working with gatherers?
Most mistakes do not throw - they quietly change the result:
- No finisher in a gatherer that buffers elements - the incomplete last batch is silently lost: 7 elements in batches of 3 give
[[1, 2, 3], [4, 5, 6]]. - Mutable state created outside the initializer - every run of the same gatherer object shares it: the second stream sees data from the first, and a parallel stream gets a data race.
- Always returning
trueafterpush()- the integrator keeps receiving elements nobody needs. Correct:return downstream.push(element);. - Expecting a value from
gather(Gatherers.fold(...))- you get a one-elementStream; assigning it to anIntegerdoes not compile. Use.findFirst().orElseThrow(). - Modifying a window from
windowFixed()/windowSliding()-UnsupportedOperationException; make a copy. ofGreedy()for an integrator that returnsfalseitself - the contract is broken, and the implementation may ignore the result.gather()on anIntStream- the method does not exist; callboxed()first:IntStream.rangeClosed(1, 10).boxed().gather(...).- Compiling on Java 21 -
cannot find symbol: gatherers exist only from Java 24 (preview in 22-23).