Stream Gatherers in Java: the gather() Method
Stream Gatherers are the mechanism for writing your own intermediate operations in the Stream API. The Stream.gather(Gatherer) method is an intermediate operation (final in Java 24, JEP 485; preview in Java 22 — JEP 461 and Java 23 — JEP 473) 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. Ready-made gatherers live in java.util.stream.Gatherers: fixed-size windows, a sliding window, a fold, a running total and a concurrent map on virtual threads.
A typical bug in a first hand-written gatherer: a "split the stream into batches of 3" operation without a finisher turns seven elements into [[1, 2, 3], [4, 5, 6]]. The seventh element is gone — no exception, no warning, because nobody sent the incomplete batch downstream. How to avoid it is shown in Batches and the finisher.
1. Why the gather() method exists
The gather() method is for intermediate operations that the standard filter(), map(), distinct(), limit() and friends do not cover: splitting a stream into batches (chunks), walking it with a sliding window, computing a running total, removing duplicates by key, stopping on a condition that depends on elements already seen. Before Java 24 such tasks were solved with workarounds — indexes, collect() followed by a new stream, or a plain loop.
The set of built-in intermediate operations is fixed (the table is in Intermediate operations). You could only extend the terminal side: a custom Collector is easy to write, while a custom intermediate operation was impossible until Java 24. Typical tasks where this hurt:
- batches (batch, chunk) — send records to the database 1000 at a time;
- sliding window — a three-day moving average of a price;
- running total — the account balance after every transaction;
- distinct by key — the first employee from each department;
- takeWhile with state — take files until their total size exceeds a limit.
Here is batching by 3 before and after gatherers:
// BatchBeforeAfter.java
import java.util.List;
import java.util.stream.Gatherers;
import java.util.stream.IntStream;
public class BatchBeforeAfter {
public static void main(String[] args) {
List<String> orders = List.of("A", "B", "C", "D", "E", "F", "G");
int size = 3;
// Before Java 24: batches via indexes - works only for a List
List<List<String>> before = IntStream.range(0, (orders.size() + size - 1) / size)
.mapToObj(i -> orders.subList(i * size, Math.min((i + 1) * size, orders.size())))
.toList();
System.out.println(before);
// Java 24+: a ready-made gatherer
List<List<String>> after = orders.stream()
.gather(Gatherers.windowFixed(size))
.toList();
System.out.println(after);
}
} [[A, B, C], [D, E, F], [G]]
[[A, B, C], [D, E, F], [G]] Same result, but the index version needs a random-access list and round-up arithmetic. For a stream that has no indexes — lines from Files.lines(), a network response, an infinite Stream.iterate() — it does not work at all. gather(Gatherers.windowFixed(3)) works with any stream and stays lazy: a batch is built only when the pipeline gets to it.
2. Gatherer vs Collector: the difference
A Collector folds the whole stream into one result and ends the pipeline; a Gatherer turns a stream into another stream and leaves the pipeline open. That is why you can call map(), filter() or another gather() after gather(), but nothing after collect(). Internally they look alike: both are described by four functions.
| Aspect | Gatherer (gather()) | Collector (collect()) |
|---|---|---|
| Operation type | Intermediate | Terminal |
| Result | Stream<R> — the pipeline continues | A single value R: a collection, a Map, a string, a number |
| Emits as it goes | Yes: downstream.push() at any moment | No: the result appears only at the end |
| Input and output | 1 → 0..N, N → 1, N → M | All elements → one value |
| Early termination | Yes: the integrator returns false; works with an infinite stream | No: a collector reads the whole stream |
| State | Optional: without an initializer the gatherer is stateless | Always: the container from the supplier |
| Parallelism | Only with a combiner; without one the stage runs sequentially | The combiner is always passed; a sequential stream never calls it |
| Four functions | initializer, integrator, combiner, finisher | supplier, accumulator, combiner, finisher |
| Factories | Gatherer.of(...), Gatherer.ofSequential(...) | Collector.of(...) |
| Ready-made implementations | Gatherers: 5 methods | Collectors: dozens of methods |
| Since | Java 24 (preview since Java 22) | Java 8 |
The key difference is the "Emits as it goes" row. A collector's accumulator only adds elements to a container; a gatherer's integrator can push something downstream right away. Everything else follows from that: since elements leave one by one, the operation can stop halfway and never read the rest of the source.
If the goal is a final object, you still need a collector: writing one with Collector.of() is covered in Writing a custom collector, and for two aggregates in a single pass there is teeing(). Reach for a gatherer when the result is again a stream of elements. The two operations combine fine in one chain: stream.gather(...).collect(...).
3. Built-in gatherers: the Gatherers class
The java.util.stream.Gatherers class (Java 24+) contains five ready-made gatherers: windowFixed() and windowSliding() split a stream into windows, fold() folds it into one value, scan() emits a running total, and mapConcurrent() applies a function concurrently on virtual threads while keeping the order. All five are sequential (created with Gatherer.ofSequential()).
| Method | What it does | Result for 1, 2, 3, 4, 5 | Edge case |
|---|---|---|---|
windowFixed(n) | Non-overlapping windows of n elements | windowFixed(2) → [1, 2], [3, 4], [5] | The last window may be shorter; n < 1 → IllegalArgumentException |
windowSliding(n) | Sliding window: each next window is shifted by one element | windowSliding(2) → [1, 2], [2, 3], [3, 4], [4, 5] | Stream shorter than the window → one window with all elements; n < 1 → IllegalArgumentException |
fold(initial, folder) | Folds all elements into one value | fold(() -> 0, Integer::sum) → 15 | Always exactly one element; on an empty stream — the initial value |
scan(initial, scanner) | Running total (prefix sum) | scan(() -> 0, Integer::sum) → 1, 3, 6, 10, 15 | The initial value is not emitted; empty stream → empty stream |
mapConcurrent(max, mapper) | A map executed on virtual threads, at most max tasks at once | The same elements map(mapper) would give, in the same order | max < 1 → IllegalArgumentException; an exception from the function is rethrown and the remaining tasks are cancelled |
Full contracts are in the Gatherers javadoc.
windowFixed(): split a stream into batches
windowFixed(n) groups consecutive elements into lists of n. If there are not enough elements for a full window, the last window is shorter, and an empty stream produces no windows at all.
// GatherersWindowDemo.java
import java.util.List;
import java.util.stream.Gatherers;
import java.util.stream.Stream;
public class GatherersWindowDemo {
public static void main(String[] args) {
List<List<Integer>> fixed = Stream.of(1, 2, 3, 4, 5, 6, 7, 8)
.gather(Gatherers.windowFixed(3))
.toList();
System.out.println(fixed);
System.out.println(Stream.<Integer>empty().gather(Gatherers.windowFixed(3)).toList());
try {
fixed.get(0).add(99); // windows are unmodifiable
} catch (UnsupportedOperationException e) {
System.out.println("window is unmodifiable: " + e.getClass().getSimpleName());
}
try {
Gatherers.windowFixed(0); // size must be at least 1
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
} [[1, 2, 3], [4, 5, 6], [7, 8]]
[]
window is unmodifiable: UnsupportedOperationException
'windowSize' must be greater than zero Every window is an unmodifiable List; the concrete list class is not guaranteed. If you need to append to a batch or sort it in place, copy it first: new ArrayList<>(window). null elements go into windows without errors. Note that IllegalArgumentException is thrown right at the call to windowFixed(0), before the stream starts running.
windowSliding(): a sliding window over a stream
windowSliding(n) emits windows of n elements, each shifted by one element from the previous. The classic use is a moving average:
// MovingAverageDemo.java
import java.util.List;
import java.util.stream.Gatherers;
import java.util.stream.Stream;
public class MovingAverageDemo {
public static void main(String[] args) {
List<Integer> prices = List.of(10, 12, 14, 13, 18, 20);
List<List<Integer>> windows = prices.stream()
.gather(Gatherers.windowSliding(3))
.toList();
System.out.println(windows);
List<Double> movingAverage = prices.stream()
.gather(Gatherers.windowSliding(3))
.map(w -> w.stream().mapToInt(Integer::intValue).average().orElseThrow())
.toList();
System.out.println(movingAverage);
// stream shorter than the window - one window with all elements
System.out.println(Stream.of(1, 2).gather(Gatherers.windowSliding(3)).toList());
}
} [[10, 12, 14], [12, 14, 13], [14, 13, 18], [13, 18, 20]]
[12.0, 13.0, 15.0, 17.0]
[[1, 2]] Six prices give four windows: 6 - 3 + 1. The last line is the edge case that is easy to forget. When the stream is shorter than the window, windowSliding() does not return an empty result — it emits one incomplete window. Code that takes exactly three elements from a window via w.get(2) fails on such input with IndexOutOfBoundsException.
fold(): a fold as an intermediate operation
fold(initial, folder) folds all elements into one value, but unlike reduce() it stays an intermediate operation: the result is a stream of one element, and you can apply map(), findFirst() or toList() to it. The fold is ordered and sequential, which is why it has no combiner.
scan(): a running total
scan(initial, scanner) applies the same kind of function as fold(), but emits every intermediate value — a prefix sum. The easiest way to see the difference is to run both on the same data, a list of account transactions:
// FoldScanDemo.java
import java.util.List;
import java.util.Optional;
import java.util.stream.Gatherers;
import java.util.stream.Stream;
public class FoldScanDemo {
public static void main(String[] args) {
List<Integer> operations = List.of(100, -30, 50, -20);
// fold: a single fold - a stream of one element
List<Integer> total = operations.stream()
.gather(Gatherers.fold(() -> 0, Integer::sum))
.toList();
System.out.println("fold: " + total);
// scan: the balance after every transaction
List<Integer> balance = operations.stream()
.gather(Gatherers.scan(() -> 0, Integer::sum))
.toList();
System.out.println("scan: " + balance);
// the result type may differ from the element type, the pipeline continues
Optional<String> report = operations.stream()
.gather(Gatherers.fold(() -> "ops:", (acc, op) -> acc + " " + op))
.map(String::toUpperCase)
.findFirst();
System.out.println(report.orElseThrow());
// what does an empty stream print?
System.out.println("fold of empty: " + Stream.<Integer>empty()
.gather(Gatherers.fold(() -> 0, Integer::sum)).toList());
System.out.println("scan of empty: " + Stream.<Integer>empty()
.gather(Gatherers.scan(() -> 0, Integer::sum)).toList());
}
} fold: [100]
scan: [100, 70, 120, 100]
OPS: 100 -30 50 -20
fold of empty: [0]
scan of empty: [] The last two lines are where people get confused. fold() emits its result in the finisher, which runs on an empty stream too, so you get the initial value [0]. scan() emits values only while processing elements and never emits the initial value by itself — on an empty stream the result is empty. The initial value is missing from a non-empty scan() output as well: the first value is 100, not 0.
fold() or reduce()
For a sum of numbers, reduce(0, Integer::sum) or mapToInt(...).sum() is simpler. fold() wins in two cases. First, when the result type differs from the element type: reduce() then needs the three-argument form with a combiner, and for an order-dependent fold (joining strings, parsing commands) a correct combiner often cannot be written at all. Second, when you want to keep the pipeline going after the fold instead of leaving the stream.
mapConcurrent(): map on virtual threads
mapConcurrent(maxConcurrency, mapper) runs the function for each element in its own virtual thread, with at most maxConcurrency tasks at a time, and emits the results in the original stream order. It is meant for functions that mostly wait: HTTP requests, database calls, file reads.
// MapConcurrentDemo.java
import java.time.Duration;
import java.util.List;
import java.util.stream.Gatherers;
import java.util.stream.Stream;
public class MapConcurrentDemo {
static String fetchUser(int id) {
try {
Thread.sleep(Duration.ofMillis(200)); // "a call to a service"
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
return "user-" + id;
}
public static void main(String[] args) {
long start = System.nanoTime();
List<String> users = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.gather(Gatherers.mapConcurrent(5, MapConcurrentDemo::fetchUser))
.toList();
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(users);
System.out.println("Time: " + ms + " ms");
try {
Stream.of(1, 2, 3, 4)
.gather(Gatherers.mapConcurrent(2, id -> {
if (id == 3) {
throw new IllegalStateException("service unavailable: " + id);
}
return id;
}))
.toList();
} catch (IllegalStateException e) {
System.out.println("Error: " + e);
}
}
} [user-1, user-2, user-3, user-4, user-5, user-6, user-7, user-8, user-9, user-10]
Time: 455 ms
Error: java.lang.IllegalStateException: service unavailable: 3 The time depends on the machine and changes from run to run, but the order of magnitude is predictable: ten 200 ms tasks with five running at once make two "waves", about 400 ms instead of the 2,000 ms a plain map() would take. The results come out in input order even if some task finishes before the one ahead of it.
Per the JDK 25 javadoc, if the function throws, the exception is rethrown from the terminal operation as a RuntimeException and the remaining tasks are cancelled. In the example the function threw IllegalStateException, which already is a RuntimeException, so it came out as is, unwrapped; an Error or a checked exception thrown behind the compiler's back arrives wrapped in a RuntimeException. mapConcurrent(0, ...) throws IllegalArgumentException immediately at the call.
The mapConcurrent() stage itself is sequential: the concurrency comes from virtual threads inside it, not from parallelStream(). For CPU-bound work it does not help, for the same reason virtual threads do not — you do not get more cores.
4. How a Gatherer works: four functions
The Gatherer<T, A, R> interface is described by four functions: the initializer creates the state, the integrator processes each element and decides whether to continue, the combiner merges the states of parallel stream segments, and the finisher runs at the end of input. Only the integrator is required. T is the input element type, A the state type (often hidden behind ?), R the output element type.
| Function | Type | When it is called | If not provided |
|---|---|---|---|
initializer() | Supplier<A> | Once per stream evaluation (in a parallel stream — once per segment) | The gatherer is stateless |
integrator() | Integrator<A, T, R> | For every element; returns boolean: false means no more elements are needed | Required |
combiner() | BinaryOperator<A> | Only in a parallel stream — to merge the states of two segments | The gatherer runs sequentially only |
finisher() | BiConsumer<A, Downstream<? super R>> | Once after the end of input — or after the integrator returned false | Nothing happens at the end |
Instead of returning a result, the integrator receives a Gatherer.Downstream object — the next stage of the pipeline. downstream.push(element) sends an element on and returns a boolean: false means the next stage will not accept any more elements (for example, it is followed by limit() or findFirst()), and every later push() will return false too. isRejecting() lets you check that in advance without sending anything; the answer is best-effort — false does not guarantee the element will be accepted.
Hence the main rule for an integrator: if it does not need to continue, return false yourself; if it pushed an element, return the result of push(). That way the "enough" signal travels from limit() back to the source, and the stream stops reading data.
Integrator.of() vs Integrator.ofGreedy()
Both factories turn a lambda into an Integrator; the difference is in the promise. Integrator.ofGreedy() creates a greedy integrator (Integrator.Greedy): it processes every element and never short-circuits on its own, only passing up a rejection from the next stage. This is a hint to the stream implementation: it may skip checking the result and take a faster execution path. Integrator.of() promises nothing and is what you need when the integrator can return false by its own logic. When in doubt, use of(): it is always correct, while ofGreedy() is only an optimisation.
You can implement the interface in your own class, but the static factories are usually enough:
| Factory | State | Parallel | Example task |
|---|---|---|---|
Gatherer.of(integrator) | No | Yes | A custom map or filter |
Gatherer.of(integrator, finisher) | No | Yes | As above, plus a trailing element at the end |
Gatherer.of(initializer, integrator, combiner, finisher) | Yes | Yes | An aggregate that can merge partial results |
Gatherer.ofSequential(integrator), ofSequential(integrator, finisher) | No | No | An operation that needs a strict call order |
Gatherer.ofSequential(initializer, integrator), ofSequential(initializer, integrator, finisher) | Yes | No | Batches, distinct by key, a sum limit |
According to the javadoc, a gatherer must not keep references to the state or to the Downstream beyond the method call they were passed to, and must not hand them to other threads. Every call to initializer(), integrator(), combiner() and finisher() must return a function with the same behaviour — that is what makes one gatherer object reusable across streams.
5. Writing a custom gatherer: four examples
A custom gatherer is written with Gatherer.of() when the operation keeps no state or can merge its state in a parallel stream, and with Gatherer.ofSequential() when it needs strict ordering. Below are four cases in order of complexity: stateless, stateful, with early termination and with a finisher. By convention a gatherer is returned from a static method, the way Gatherers and Collectors do it.
Stateless: your own map and filter
The simplest gatherer has no initializer, only an integrator. That is enough to reimplement map() and filter(); in practice this is a teaching example, but it shows well how an integrator emits one element (map) or none (filter) per input element.
// CustomMapFilterDemo.java
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Gatherer;
import java.util.stream.Stream;
public class CustomMapFilterDemo {
static <T, R> Gatherer<T, ?, R> map(Function<? super T, ? extends R> mapper) {
return Gatherer.of(Gatherer.Integrator.<Void, T, R>ofGreedy(
(state, element, downstream) -> downstream.push(mapper.apply(element))));
}
static <T> Gatherer<T, ?, T> filter(Predicate<? super T> predicate) {
return Gatherer.of(Gatherer.Integrator.<Void, T, T>ofGreedy((state, element, downstream) -> {
if (predicate.test(element)) {
return downstream.push(element);
}
return true; // element skipped, but keep reading
}));
}
public static void main(String[] args) {
List<Integer> lengths = Stream.of("sun", "pool", "beach")
.gather(map(String::length))
.toList();
System.out.println(lengths);
List<Integer> even = Stream.of(1, 2, 3, 4, 5, 6)
.gather(filter(n -> n % 2 == 0))
.toList();
System.out.println(even);
}
} [3, 4, 5]
[2, 4, 6] The state parameter is unused here: a gatherer without an initializer has state of type Void. Both gatherers are built with Gatherer.of(), so in a parallel stream they run in parallel, just like the regular map() and filter(). The integrators are greedy: they never stop the stream themselves, and return true in filter means "keep going", not "stop".
Stateful: distinctBy a key
The standard distinct() compares whole elements with equals(). To keep one element per key — say, the first employee from each department — you have to remember the keys already seen. That is state, and it is created in the initializer:
// DistinctByDemo.java
import java.util.HashSet;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Gatherer;
public class DistinctByDemo {
record Employee(String name, String department) { }
static <T, K> Gatherer<T, ?, T> distinctBy(Function<? super T, ? extends K> keyExtractor) {
return Gatherer.ofSequential(
() -> new HashSet<K>(), // a new set for every evaluation
Gatherer.Integrator.<HashSet<K>, T, T>ofGreedy((seen, element, downstream) -> {
if (seen.add(keyExtractor.apply(element))) {
return downstream.push(element); // first time we see this key
}
return true;
}));
}
public static void main(String[] args) {
List<Employee> staff = List.of(
new Employee("Anna", "IT"),
new Employee("Ben", "IT"),
new Employee("Clara", "HR"),
new Employee("Dave", "Sales"),
new Employee("Emma", "Sales"));
List<String> firstInDepartment = staff.stream()
.gather(distinctBy(Employee::department))
.map(Employee::name)
.toList();
System.out.println(firstInDepartment);
}
} [Anna, Clara, Dave] Why ofSequential(): "first in the department" only makes sense with a strict order, and HashSet is not thread-safe. Without gatherers the same task was solved with Collectors.toMap(key, e -> e, (a, b) -> a, LinkedHashMap::new) and values(). But a collector reads the whole stream and builds a map, while distinctBy is lazy: combined with limit() or findFirst() it reads exactly as many elements as needed.
Early termination: a sum limit
An integrator that returns false tells the stream "no more elements needed". This is how you write a stateful takeWhile — for example, take files until their total size exceeds a limit. The integrator here is created with Integrator.of(), not ofGreedy(), because it stops the stream itself.
// SumLimitDemo.java
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Gatherer;
import java.util.stream.Stream;
public class SumLimitDemo {
static Gatherer<Integer, ?, Integer> takeWhileSumAtMost(int limit) {
return Gatherer.ofSequential(
() -> new int[1], // sum of the elements passed so far
Gatherer.Integrator.<int[], Integer, Integer>of((sum, size, downstream) -> {
if (sum[0] + size > limit) {
return false; // stop: don't read the source any further
}
sum[0] += size;
return downstream.push(size);
}));
}
public static void main(String[] args) {
List<Integer> fileSizes = List.of(400, 300, 200, 500, 100);
System.out.println(fileSizes.stream().gather(takeWhileSumAtMost(1000)).toList());
// the infinite stream 1, 2, 3, ... terminates too
AtomicInteger read = new AtomicInteger();
List<Integer> naturals = Stream.iterate(1, n -> n + 1)
.peek(n -> read.incrementAndGet())
.gather(takeWhileSumAtMost(20))
.toList();
System.out.println(naturals);
System.out.println("elements read: " + read.get());
}
} [400, 300, 200]
[1, 2, 3, 4, 5]
elements read: 6 Like takeWhile() (see Intermediate operations), the gatherer stops at the first element that fails the check: the 100-byte file at the end of the list would fit within the limit, but the stream never gets to it. On the infinite stream six elements were read: five brought the sum to 15, six would have pushed it past 20, the integrator returned false, and Stream.iterate() generated nothing more. Had the integrator returned true instead of false and simply stopped pushing elements, this pipeline would never finish.
Batches and the finisher
The finisher runs once at the end of input and receives the state and the Downstream. You need it when the state may still hold data that has not been sent yet: an incomplete last batch, an accumulated total. Here is a simplified windowFixed — first without a finisher, then with one:
// BatchGathererDemo.java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Gatherer;
public class BatchGathererDemo {
// shared integrator for both versions: buffers elements and pushes a full batch
static <T> Gatherer.Integrator<ArrayList<T>, T, List<T>> fill(int size) {
return Gatherer.Integrator.ofGreedy((buffer, element, downstream) -> {
buffer.add(element);
if (buffer.size() < size) {
return true;
}
List<T> full = new ArrayList<>(buffer);
buffer.clear();
return downstream.push(full);
});
}
// BUG: no finisher - the incomplete last batch is lost
static <T> Gatherer<T, ?, List<T>> batchWithoutFinisher(int size) {
return Gatherer.ofSequential(() -> new ArrayList<T>(size), fill(size));
}
static <T> Gatherer<T, ?, List<T>> batch(int size) {
if (size < 1) {
throw new IllegalArgumentException("size must be positive: " + size);
}
return Gatherer.ofSequential(
() -> new ArrayList<T>(size),
fill(size),
(buffer, downstream) -> { // finisher: input is over
if (!buffer.isEmpty() && !downstream.isRejecting()) {
List<T> last = new ArrayList<>(buffer);
downstream.push(last);
}
});
}
public static void main(String[] args) {
List<Integer> ids = List.of(1, 2, 3, 4, 5, 6, 7);
System.out.println(ids.stream().gather(batchWithoutFinisher(3)).toList());
System.out.println(ids.stream().gather(batch(3)).toList());
}
} [[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6], [7]] The integrator pushes a batch only when it is full, so the 7 stays in the buffer. Without a finisher the stream ends and the buffer is thrown away together with it. The isRejecting() check in the finisher is not needed for correctness, but it saves work when the next stage has already stopped accepting elements. The size check in batch() runs before the gatherer is created, as in Gatherers.windowFixed(): it is better to fail at the call than when the stream starts. The built-in windowFixed() does all of this and also returns unmodifiable windows, so in production code write your own version only when you need something different — for example, batches by total size rather than by count.
6. Composition: andThen() and chained gather() calls
Two gatherers are combined into one with andThen(): a.andThen(b) feeds the output of a into b. The result is the same as the chain .gather(a).gather(b), but the composed gatherer is an ordinary object: you can store it in a constant, return it from a method and reuse it.
// AndThenDemo.java
import java.util.List;
import java.util.stream.Gatherer;
import java.util.stream.Gatherers;
import java.util.stream.Stream;
public class AndThenDemo {
public static void main(String[] args) {
Gatherer<Integer, ?, Integer> runningTotal = Gatherers.scan(() -> 0, Integer::sum);
Gatherer<Integer, ?, List<Integer>> pairs = Gatherers.windowFixed(2);
Gatherer<Integer, ?, List<Integer>> totalsInPairs = runningTotal.andThen(pairs);
System.out.println(Stream.of(1, 2, 3, 4, 5).gather(totalsInPairs).toList());
System.out.println(Stream.of(1, 2, 3, 4, 5).gather(runningTotal).gather(pairs).toList());
}
} [[1, 3], [6, 10], [15]]
[[1, 3], [6, 10], [15]] The running total 1, 3, 6, 10, 15 is split into pairs — identically both ways. The example also shows that runningTotal and pairs are safe to reuse: the initializer creates fresh state for every stream. That holds as long as the gatherer is written correctly — a counterexample is in Common mistakes.
If both gatherers are stateless with greedy integrators, the JDK's andThen() implementation fuses them into a single call without intermediate state. A composed gatherer is parallelizable only if both parts are: one sequential part is enough to make the whole stage sequential.
7. Gatherers in parallel streams
A gatherer without a combiner (created with ofSequential()) runs sequentially in a parallel stream — on its own section of the pipeline, preserving order and producing the correct result. To make the stage run in parallel you need a combiner: Gatherer.of(initializer, integrator, combiner, finisher). Then each segment of the input gets its own state, and the combiner merges them before the finisher.
All five built-in gatherers — windowFixed, windowSliding, fold, scan, mapConcurrent — are created with Gatherer.ofSequential() in JDK 25. That is not a flaw: windows and running totals depend on order by definition and cannot be split into independent parts.
// ParallelGathererDemo.java
import java.util.List;
import java.util.stream.Gatherer;
import java.util.stream.Gatherers;
import java.util.stream.IntStream;
public class ParallelGathererDemo {
// a parallelizable gatherer: it has a combiner
static Gatherer<Integer, ?, Long> sum() {
return Gatherer.of(
() -> new long[1],
Gatherer.Integrator.<long[], Integer, Long>ofGreedy((acc, n, downstream) -> {
acc[0] += n;
return true;
}),
(left, right) -> { // combiner: merge the states of two segments
left[0] += right[0];
return left;
},
(acc, downstream) -> downstream.push(acc[0]));
}
public static void main(String[] args) {
List<Integer> numbers = IntStream.rangeClosed(1, 1_000).boxed().toList();
System.out.println(numbers.parallelStream().gather(sum()).toList());
// a sequential gatherer in a parallel stream: order and result are correct
List<List<Integer>> windows = numbers.parallelStream()
.gather(Gatherers.windowFixed(400))
.toList();
System.out.println(windows.size() + " windows, the last one starts with " + windows.getLast().getFirst());
}
} [500500]
3 windows, the last one starts with 801 The sum() integrator pushes nothing: the result appears in the finisher, which runs once on the merged state. The combiner must give the same result as sequential processing — true for a sum, but not for "first element per key", which is why distinctBy above stayed sequential. As with a collector, a bug in the combiner is invisible in a sequential stream: test your gatherer on parallelStream() too.
State belongs in the initializer
In a parallel stream the integrator is never called concurrently on the same state object: each segment works with its own state, and merging happens only after both segments are done. So plain ArrayList, HashSet and arrays are fine inside the state without synchronization. The guarantee does not extend to objects captured by a lambda from outside: a shared HashSet created outside the initializer causes a data race in a parallel stream.
8. Common mistakes with gatherers
Most bugs in custom gatherers do not throw — they quietly change the result: the last batch disappears, a second run sees data from the first, the stream reads more than it should. Here are the typical ones and how to fix them.
| What people do | What happens | The fix |
|---|---|---|
| Buffer elements in the state but write no finisher | The incomplete last batch is silently lost | A finisher that pushes the remainder (batches and the finisher) |
| Create mutable state outside the initializer | All runs of the gatherer share one state: the second stream sees the first one's data; in a parallel stream — a data race | Create state only in the initializer |
Push an element with push() and always return true | The integrator may keep receiving elements nobody needs any more | return downstream.push(element); |
Expect a value from gather(Gatherers.fold(...)) | You get a Stream of one element; assigning it to an Integer does not compile | .findFirst().orElseThrow() or .toList().getFirst() |
Modify a window from windowFixed()/windowSliding() | UnsupportedOperationException | new ArrayList<>(window) |
Create an integrator with ofGreedy() that itself returns false | The contract is broken: the implementation may ignore the result and keep the stream going | Integrator.of() for anything that short-circuits |
Call gather() on an IntStream | Compilation error: the method does not exist | intStream.boxed().gather(...) |
| Compile on Java 21 | cannot find symbol: neither gather() nor java.util.stream.Gatherer exists | Java 24+ (which version you need) |
The second row is the nastiest, because the first run works correctly. Gatherers are often stored in constants and reused, and state captured by a lambda outlives the stream:
// SharedStateBugDemo.java
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Gatherer;
import java.util.stream.Stream;
public class SharedStateBugDemo {
static <T> Gatherer<T, ?, T> distinctBroken() {
Set<T> seen = new HashSet<>(); // BUG: one set for all runs
return Gatherer.ofSequential(
Gatherer.Integrator.<Void, T, T>ofGreedy((state, element, downstream) -> {
if (seen.add(element)) {
return downstream.push(element);
}
return true;
}));
}
public static void main(String[] args) {
Gatherer<String, ?, String> unique = distinctBroken();
System.out.println(Stream.of("a", "b", "a").gather(unique).toList());
System.out.println(Stream.of("a", "c").gather(unique).toList());
}
} [a, b]
[c] In the second stream "a" appears for the first time, yet the gatherer dropped it: the set is left over from the first run. The fix is to move new HashSet<>() into the initializer, as in distinctBy.
9. Which Java version you need
Stream.gather(), the Gatherer interface and the Gatherers class are available without flags starting with Java 24. Java 25 is the first LTS release with gatherers; Java 21 LTS does not have them. In Java 22 and 23 the API was a preview feature and worked only with --enable-preview.
| Version | Gatherers status | What you need to run them |
|---|---|---|
| Java 21 (LTS) | Not available | Not available; alternatives are in the FAQ |
| Java 22 | Preview (JEP 461) | javac --release 22 --enable-preview, java --enable-preview |
| Java 23 | Second preview (JEP 473) | --release 23 --enable-preview |
| Java 24 | Final (JEP 485) | No flags |
| Java 25 (LTS) | Final | No flags; the first LTS with gatherers |
According to the text of JEP 473 and JEP 485, the API carried over unchanged in the second preview and at finalization, so the examples in this lesson also compile on Java 22–23 with the preview flags. But a class compiled with --enable-preview runs only on the exact JDK version it was built for — not an option for a production project. If your project is on Java 21 and a move to 25 is planned, write your batching and windowing utilities so they can later be replaced with a single gather(Gatherers.windowFixed(n)) line. The API description and motivation are in JEP 485.
Frequently asked questions
What is the difference between gather() and collect()?
gather() is an intermediate operation: it returns a new Stream, the pipeline continues after it, elements are emitted as they are processed, and processing can stop early. collect() is terminal: it reads the whole stream and returns one value. A full comparison across ten aspects is in Gatherer vs Collector.
Can I use gatherers in Java 21?
No: Java 21 has neither the gather() method nor the Gatherer and Gatherers types, and the preview only appeared in Java 22. On Java 21, batches from a list are built with indexes and subList() (example in Why the gather() method exists) or with a library such as Guava's Lists.partition(); a sliding window and a running total — with a plain loop. For an arbitrary stream you are left with iterator() and manual traversal.
Do gatherers work with IntStream?
Not directly: gather() is declared only on Stream<T>; IntStream, LongStream and DoubleStream do not have it. Box the elements with boxed() first: IntStream.rangeClosed(1, 10).boxed().gather(Gatherers.windowFixed(3)). If you need numeric operations afterwards, go back to primitives with mapToInt().
How do I process a large file in batches of 1000 lines?
Open Files.lines(path) in try-with-resources, call gather(Gatherers.windowFixed(1000)), then forEach(batch -> repository.saveAll(batch)). The file is read lazily: only one batch is held in memory at a time, not the whole file, and the last batch may have fewer than 1000 lines. The index approach with subList() does not fit here — it needs all lines loaded into a list first.
Is a gatherer thread-safe in a parallel stream?
State created in the initializer is: each segment of the input has its own state, the integrator is never called on it from two threads at once, and the combiner merges states after the segments are processed. A gatherer without a combiner runs sequentially in a parallel stream anyway. What is not safe is anything the lambdas capture from outside: a shared collection, a counter, a class field. Details are in Gatherers in parallel streams.
Practice
Reinforce this lesson with hands-on tasks, each with a level and a time estimate.
- Batches, moving average and balance: built-in Gatherers
- A custom Gatherer: drop repeats and group runs
- mapConcurrent: concurrent calls to a slow service
Comments