Java Reference ยท Streams and Functional
Java stream gatherers
Reference for Java 24 stream gatherers: Stream.gather() with Gatherers.windowFixed, windowSliding, fold, scan and mapConcurrent, plus writing your own.
A gatherer is a user-definable intermediate operation for streams. Streams already had a fixed menu (map, filter, limit and so on) while Collector let you define terminal reductions. Gatherers, final in Java 24 (JEP 485), fill the gap: they can keep state, emit any number of outputs per input and even stop early.
You apply one with Stream.gather(gatherer). The class java.util.stream.Gatherers offers ready-made ones, and Gatherer.ofSequential() lets you build your own.
Stream.of(1, 2, 3, 4, 5).gather(Gatherers.windowFixed(2)).toList(); // [[1, 2], [3, 4], [5]]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
<R> Stream<R> gather(Gatherer<? super T, ?, R> gatherer)
Built-in factories in Gatherers:
| Method | Description |
|---|---|
windowFixed(int size) |
Groups elements into non-overlapping lists of size; the last list may be shorter. |
windowSliding(int size) |
Emits every list of size consecutive elements, moving one step each time. |
fold(initial, folder) |
Reduces everything to one value, emitted when the input ends. |
scan(initial, scanner) |
Emits the running value after each element. |
mapConcurrent(maxConcurrency, mapper) |
Maps on virtual threads, at most maxConcurrency at once, keeping order. |
A custom gatherer is built from up to four functions: an initializer (creates state), an integrator (receives each element and a Downstream; return false to stop), an optional combiner for parallel use and a finisher (runs at the end).
Usage notes
- Version: preview in Java 22 and 23, final in Java 24. The examples run on Java 25 without any flags.
- Mutable state is private: the state object belongs to one gatherer run. Keep it inside the gatherer, never share it.
- Return value of
push:downstream.push(x)returnsfalsewhen the consumer wants no more input. Return that value from your integrator to stop reading early. - Sequential vs parallel:
Gatherer.ofSequentialforces sequential processing of the gatherer's own step. Pass a combiner toGatherer.ofonly if the operation can truly be split. - Windows keep copies: the emitted window lists are fresh lists, safe to store.
mapConcurrent: useful for blocking calls; the sandbox here has one CPU, so expect no speed-up in the TryIt.- Compose:
a.andThen(b)feeds the output ofaintob.