Java Stream Gatherers: windowFixed, windowSliding, fold, scan and mapConcurrent
Use Java 24's stream gatherers, the extension point for intermediate operations. Group elements with windowFixed and windowSliding, compare neighbors, fold and scan sequentially, run blocking calls on virtual threads with mapConcurrent, and chain gatherers with andThen.
kvi5hnuCode Sprout team member9 min readOn this page
For terminal operations, the stream API has always had an extension point: collect accepts any Collector, so you can write your own (article 12). Intermediate operations had no such hook. If filter, map, flatMap and friends didn't do what you needed, such as grouping elements into batches of 100 or comparing each element with the previous one, you were stuck.
Gatherers fill that gap. They were previewed in Java 22 and 23 and became final in Java 24 (JEP 485). The new Stream.gather method takes a Gatherer and turns a stream into another stream, possibly with a different element type and a different number of elements. This article covers the ready-made gatherers in the Gatherers class. The next article shows how to write your own.
Fixed and sliding windows
windowFixed(n) groups consecutive elements into lists of n. The last window may be shorter:
IntStream.range(0, 10).boxed().gather(Gatherers.windowFixed(4)).toList()
// [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
That's exactly what you need for batching, such as inserting rows into a database 500 at a time.
windowSliding(n) produces overlapping windows: each one moves forward by a single element:
IntStream.range(0, 7).boxed().gather(Gatherers.windowSliding(4)).toList()
// [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
If the stream has fewer than n elements, windowSliding yields a single window containing all of them, and an empty stream yields no windows. Both window gatherers need a window size of at least 1. The lists are unmodifiable.

Comparing neighbors
Sliding windows of size 2 let you look at each element together with its successor, which was awkward with streams before. Differences between consecutive readings are a one-liner:
readings.stream().gather(Gatherers.windowSliding(2)).map(w -> w.get(1) - w.get(0))
Here's how to drop adjacent duplicates, treating words that differ only in case as equal:
Stream.concat(words, Stream.of((String) null))
.gather(Gatherers.windowSliding(2))
.filter(w -> !w.get(0).equalsIgnoreCase(w.get(1)))
.map(w -> w.get(0))
A window [a, b] passes when a and its successor differ, so the filter keeps the last word of each run of duplicates. The final word has no successor and would never appear in a window as w.get(0), so a null sentinel is appended. equalsIgnoreCase(null) is false, which lets the last word through.
fold and scan
A fold starts with an initial value and applies an operation to the running result and each element in turn: (((init op v₀) op v₁) op v₂) …. That looks like reduce (article 13), but there's an important difference. A reduction is designed to be split up for parallel execution, so its operation must be associative. A fold is inherently sequential, so the operation can be anything. Any loop that updates a running value can be written as a fold, such as turning decimal digits into a number:
int n = 0;
for (int d : digits) n = 10 * n + d;
int n = digits.stream()
.gather(Gatherers.fold(() -> 0, (x, d) -> x * 10 + d))
.findFirst()
.orElse(0);
The operation x * 10 + d isn't associative, so reduce would give wrong answers in parallel. A fold is safe because it processes the elements one at a time, in order, even when the rest of the pipeline is parallel.
fold takes a supplier for the initial value (so each use gets a fresh one) and the folding function. It produces a stream with exactly one element, the final value. For an empty input, that element is the initial value. Since a gatherer has to produce a stream, you need findFirst() or toList() to get the value out.
scan is like fold, but it emits every intermediate result, not just the last one. It's the classic "running total":
Stream.of(1, 7, 2, 9).gather(Gatherers.scan(() -> 0, (x, d) -> x * 10 + d)).toList()
// [1, 17, 172, 1729]
Stream.of(5, 3, 8, 1).gather(Gatherers.scan(() -> 0, Integer::sum)).toList()
// [5, 8, 16, 17]
The initial value itself isn't emitted, so the output has the same number of elements as the input.
mapConcurrent
mapConcurrent(maxConcurrency, mapper) is like map, but runs the mapper calls concurrently, each in its own virtual thread, with at most maxConcurrency calls in flight at once. It's made for work that mostly waits, such as HTTP calls, file or database access:
List<String> contents = urls.stream()
.gather(Gatherers.mapConcurrent(100, this::read))
.toList();
Things to know:
- The results come out in the original encounter order, regardless of which call finishes first.
maxConcurrencylimits the load on whatever service you're calling, a built-in throttle.- If a call throws, the remaining calls are cancelled (their threads are interrupted) and the exception is rethrown from the stream operation.
- The mapper may block freely. Blocking a virtual thread is cheap, which is the whole point.
Don't confuse this with parallel streams (article 17). Parallel streams spread CPU-bound work across the processor cores, using a small pool of platform threads. Blocking in a parallel stream ties up those few threads. mapConcurrent is for I/O-bound work and can have hundreds of calls waiting at once at almost no cost. The demo simulates five slow calls of 200 ms each with Thread.sleep. Run concurrently, they finish together in about 200 ms rather than one second.
Composing gatherers
Gatherers combine in two ways. You can simply call gather several times in a pipeline, or you can compose two gatherers into one with andThen, which is useful when you want to name and reuse the combination:
var pairSums = Gatherers.<Integer>windowFixed(2)
.andThen(Gatherers.scan(() -> 0, (Integer acc, List<Integer> w) -> acc + w.get(0) + w.get(w.size() - 1)));
Gatherers are lazy like all intermediate operations, so they work on infinite streams as long as something downstream, such as limit, eventually stops the pipeline.
A complete example
import java.util.*;
import java.util.stream.*;
public class Solution {
static String slowUpperCase(String s) {
try {
Thread.sleep(200); // pretend this is a slow, blocking call
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return s.toUpperCase() + (Thread.currentThread().isVirtual() ? " (virtual)" : "");
}
public static void main(String[] args) {
// fixed and sliding windows
System.out.println("windowFixed(4): "
+ IntStream.range(0, 10).boxed().gather(Gatherers.windowFixed(4)).toList());
System.out.println("windowSliding(4): "
+ IntStream.range(0, 7).boxed().gather(Gatherers.windowSliding(4)).toList());
System.out.println("windowSliding(4) of 2 elements: "
+ Stream.of(1, 2).gather(Gatherers.windowSliding(4)).toList());
// compare neighbors: drop adjacent duplicates
Stream<String> words = Stream.of("the", "The", "cat", "sat", "sat", "SAT", "on", "the", "mat");
List<String> deduped = Stream.concat(words, Stream.of((String) null))
.gather(Gatherers.windowSliding(2))
.filter(w -> !w.get(0).equalsIgnoreCase(w.get(1)))
.map(w -> w.get(0))
.toList();
System.out.println("adjacent duplicates removed: " + deduped);
// differences between neighbors
List<Integer> readings = List.of(10, 13, 13, 9, 15);
System.out.println("changes: " + readings.stream().gather(Gatherers.windowSliding(2))
.map(w -> w.get(1) - w.get(0)).toList());
// fold: digits to number, inherently sequential
List<Integer> digits = List.of(1, 7, 2, 9);
int n = digits.stream().gather(Gatherers.fold(() -> 0, (x, d) -> x * 10 + d)).findFirst().orElse(0);
System.out.println("fold: " + n);
System.out.println("fold of nothing: "
+ Stream.<Integer>empty().gather(Gatherers.fold(() -> 0, (x, d) -> x * 10 + d)).toList());
// scan: every intermediate result
System.out.println("scan: " + digits.stream().gather(Gatherers.scan(() -> 0, (x, d) -> x * 10 + d)).toList());
System.out.println("running total: "
+ Stream.of(5, 3, 8, 1).gather(Gatherers.scan(() -> 0, Integer::sum)).toList());
// gatherers are lazy and work on infinite streams
System.out.println("first three windows of an infinite stream: "
+ Stream.iterate(1, i -> i + 1).gather(Gatherers.windowFixed(3)).limit(3).toList());
// composing gatherers with andThen
var pairSums = Gatherers.<Integer>windowFixed(2)
.andThen(Gatherers.scan(() -> 0, (Integer acc, List<Integer> w) -> acc + w.get(0) + w.get(w.size() - 1)));
System.out.println("andThen: " + Stream.of(1, 2, 3, 4, 5, 6).gather(pairSums).toList());
// mapConcurrent: blocking work on virtual threads, results in encounter order
long start = System.nanoTime();
List<String> results = Stream.of("alpha", "beta", "gamma", "delta", "epsilon")
.gather(Gatherers.mapConcurrent(5, Solution::slowUpperCase))
.toList();
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println("mapConcurrent: " + results);
System.out.println("five 200 ms calls finished in under 1 second: " + (millis < 1000));
// an exception in one task cancels the others and is rethrown
try {
Stream.of(1, 2, 0, 4).gather(Gatherers.mapConcurrent(4, x -> 12 / x)).toList();
} catch (ArithmeticException e) {
System.out.println("mapConcurrent rethrew: " + e);
}
}
}
windowFixed(4): [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
windowSliding(4): [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
windowSliding(4) of 2 elements: [[1, 2]]
adjacent duplicates removed: [The, cat, SAT, on, the, mat]
changes: [3, 0, -4, 6]
fold: 1729
fold of nothing: [0]
scan: [1, 17, 172, 1729]
running total: [5, 8, 16, 17]
first three windows of an infinite stream: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
andThen: [3, 10, 21]
mapConcurrent: [ALPHA (virtual), BETA (virtual), GAMMA (virtual), DELTA (virtual), EPSILON (virtual)]
five 200 ms calls finished in under 1 second: true
mapConcurrent rethrew: java.lang.ArithmeticException: / by zero
Notice that the adjacent-duplicates example keeps "The" and "SAT", the last word of each run. The mapConcurrent timing is reported as a yes/no check because exact times vary between runs.
Common questions
Which Java version do I need for gatherers?
Java 24 or later. In Java 22 and 23 they were a preview feature that required --enable-preview; since Java 24 they are a regular part of the API.
Do gatherers work with parallel streams?
Yes, and the result is always correct. A gatherer that provides a combiner can itself be evaluated in parallel. A gatherer without one, which includes all five predefined gatherers, is evaluated sequentially, in encounter order, while the other stages of the pipeline can still run in parallel. So a parallel stream with fold or windowFixed works, but that stage gains no speedup.
Should I use mapConcurrent, an ExecutorService or CompletableFuture?
For "call a blocking service for each element, with at most n calls at a time, results in order", mapConcurrent is the shortest correct solution. An ExecutorService with virtual threads gives you more control: individual futures, timeouts and partial results. Structured concurrency (StructuredTaskScope, a preview API) suits a fixed set of related subtasks. Use CompletableFuture for asynchronous chains that must not block a thread at all.
Does windowFixed keep the whole stream in memory?
No, only the current window. A stream of a million rows with windowFixed(500) holds at most 500 rows in a window at a time, which makes it suitable for batch inserts. windowSliding likewise keeps one window.
Where are the other gatherers I expected, such as distinctBy or zip?
The JDK ships only the five in Gatherers. Others are easy to write yourself (next article), and libraries collect common ones.
API reference
java.util.stream.Stream<T>
| Method | Description |
|---|---|
<R> Stream<R> gather(Gatherer<? super T, ?, R> gatherer) (Java 24) | an intermediate operation that processes the elements with the gatherer |
java.util.stream.Gatherers (Java 24)
| Method | Description |
|---|---|
windowFixed(int windowSize) | consecutive, non-overlapping windows as unmodifiable lists; the last may be shorter |
windowSliding(int windowSize) | overlapping windows that advance by one element |
fold(Supplier<R> initial, BiFunction<? super R, ? super T, ? extends R> folder) | a one-element stream with the result of sequentially folding all elements |
scan(Supplier<R> initial, BiFunction<? super R, ? super T, ? extends R> scanner) | every intermediate result of a sequential fold |
mapConcurrent(int maxConcurrency, Function<? super T, ? extends R> mapper) | maps elements concurrently on virtual threads, preserving encounter order |
java.util.stream.Gatherer<T, A, R>
| Method | Description |
|---|---|
<RR> Gatherer<T, ?, RR> andThen(Gatherer<? super R, ?, ? extends RR> that) | a gatherer that applies this gatherer, then that |
Summary
Stream.gather(final in Java 24) is the extension point for intermediate operations, ascollectis for terminal ones.windowFixedbatches elements.windowSlidinggives overlapping windows that make neighbor comparisons easy.foldandscanapply a non-associative operation sequentially.foldyields only the final value,scanevery intermediate value.mapConcurrentruns blocking mapper calls on virtual threads with bounded concurrency, keeping encounter order and cancelling the rest on failure.- Gatherers are lazy, chain with repeated
gathercalls orandThen, and work on infinite streams.
Practice Questions
What does Stream.of(1, 2, 3, 4, 5).gather(Gatherers.windowFixed(2)).toList() return?
[[1, 2], [3, 4], [5]]. The last window holds the single leftover element.
Using a gatherer, check whether a List<Integer> is sorted in ascending order.
list.stream().gather(Gatherers.windowSliding(2)).allMatch(w -> w.size() < 2 || w.get(0) <= w.get(1)). Each window holds a pair of neighbors. The size check handles a one-element list, whose only window has a single element.
Why is fold safe for the operation x * 10 + d when reduce isn't?
reduce may split the stream into chunks and combine them in a different grouping, which requires an associative operation. x * 10 + d isn't associative. fold always processes elements sequentially, in order, so the grouping never changes.
Give the running maximum of Stream.of(3, 1, 4, 1, 5, 9, 2) using a gatherer.
Stream.of(3, 1, 4, 1, 5, 9, 2).gather(Gatherers.scan(() -> Integer.MIN_VALUE, Math::max)).toList() gives [3, 3, 4, 4, 5, 9, 9].
You need to fetch 10,000 web pages. Why is mapConcurrent a better fit than a parallel stream?
Fetching is I/O-bound: each call mostly waits for the network. A parallel stream uses only about as many threads as there are cores, so most of them sit blocked. mapConcurrent runs each fetch in a cheap virtual thread, keeps up to maxConcurrency requests in flight, and still returns results in order.
Previous: Java Stream reduce: Identity, Accumulator, Combiner and Three-Argument collect
Next: Implementing Java Stream Gatherers: Integrators, State, Short-Circuiting and Parallelism
Related reading
- 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
- Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads

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.