Stream gatherers

A gatherer is a custom intermediate stream operation. Stream.gather lets you add operations the Stream API does not have, such as grouping elements into windows, keeping running state or stopping early, and java.util.stream.Gatherers provides five ready-made ones. This page explains the four functions a gatherer is made of, runs the built-in ones, writes custom gatherers with and without finishers, and measures laziness and cost.

Contents

What a gatherer is

A stream pipeline has a source, any number of intermediate operations and one terminal operation. Since Java 8 the intermediate operations have been a fixed set: map, filter, flatMap, distinct, sorted, limit, and later takeWhile, dropWhile (Java 9) and mapMulti (Java 16). Anything else, such as "group into chunks of 3", "average over a sliding window" or "stop when the values stop increasing", had to be done with a collector at the end, which reads the whole stream, or with loops outside the stream.

Stream.gather(gatherer) is a general hook for intermediate operations, in the way collect(collector) is a general hook for terminal ones. A Gatherer<T, A, R> takes elements of type T, keeps private state of type A, and emits elements of type R. It is defined by up to four functions:

  • Initializer: creates the state object, once per evaluation of the stream.
  • Integrator: called for each element with the state, the element and a Downstream. It may push zero, one or many elements downstream, and returns false to stop the stream early.
  • Combiner: merges two states, which allows the gatherer to run on a parallel stream. Without it, the gatherer runs sequentially even in a parallel pipeline.
  • Finisher: called after the last element, and may push final elements, such as a partly filled batch.

Because the integrator is pulled one element at a time, a gatherer stays lazy: it works on infinite streams and reads only what the rest of the pipeline asks for. Gatherers can be chained with andThen into one gatherer, and ordinary operations can follow them.

Intermediate operations and gatherers, by version
FeatureSinceBest for
map, filter, flatMap, limit and friendsJava 8One element in, zero or one or many out, no state
takeWhile, dropWhileJava 9Stopping or skipping on a condition
mapMultiJava 16Emitting several elements per input without creating streams
Stream.gather preview (JEP 461, JEP 473)Java 22, 23Historical
Stream.gather and Gatherers standard (JEP 485)Java 24Windows, running state, early stop, bounded concurrency

The programs below were run on JDK 25 and need JDK 24 or later, with no preview flags.

The built-in gatherers

The class java.util.stream.Gatherers has five factory methods. The program applies four of them to the numbers 1 to 7. An odd count was chosen so that windowFixed(3) leaves a short last window.

Java
import java.util.List;
import java.util.stream.Gatherers;
import java.util.stream.Stream;

public class BuiltInGatherers {

    public static void main(String[] args) {
        List<Integer> data = List.of(1, 2, 3, 4, 5, 6, 7);

        // Fixed windows: chunks of 3, the last one may be shorter
        System.out.println("windowFixed(3):   "
                + data.stream().gather(Gatherers.windowFixed(3)).toList());

        // Sliding windows: each window moves forward by one element
        System.out.println("windowSliding(3): "
                + data.stream().gather(Gatherers.windowSliding(3)).toList());

        // Moving average over the sliding windows
        List<Double> movingAvg = data.stream()
                .gather(Gatherers.windowSliding(3))
                .map(w -> w.stream().mapToInt(Integer::intValue).average().orElseThrow())
                .toList();
        System.out.println("3-point average:  " + movingAvg);

        // scan: running results, one output per input
        System.out.println("scan (running sum): "
                + data.stream().gather(Gatherers.scan(() -> 0, Integer::sum)).toList());

        // fold: one final result, emitted as a single-element stream
        System.out.println("fold (joined):    " + Stream.of("a", "b", "c")
                .gather(Gatherers.fold(() -> "", (acc, s) -> acc + s)).toList());
    }
}

Output:

Output
windowFixed(3):   [[1, 2, 3], [4, 5, 6], [7]]
windowSliding(3): [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]]
3-point average:  [2.0, 3.0, 4.0, 5.0, 6.0]
scan (running sum): [1, 3, 6, 10, 15, 21, 28]
fold (joined):    [abc]
Gatherers factory methods
MethodOutputFrom the run above
windowFixed(n)Lists of n elements; the last may be shorter7 elements give windows of 3, 3 and 1
windowSliding(n)Every run of n consecutive elements7 elements give 7 - 3 + 1 = 5 windows
scan(init, f)The running result after each element1, 1+2=3, 3+3=6, and so on to 28
fold(init, f)One final result, as a one-element stream[abc]
mapConcurrent(n, f)f applied in up to n virtual threads at onceSee below

The moving average combines a gatherer with ordinary stream operations: each window of three becomes its average, so 1, 2, 3 gives 2.0, and so on.

mapConcurrent: bounded parallel I/O

mapConcurrent(maxConcurrency, function) runs the function on virtual threads, at most maxConcurrency at a time, and emits results in the original order. That fits calling a remote service for each element without overloading it, which parallel() is not designed for.

The program "fetches" 12 items with a limit of 4. Each call sleeps 200 - 10 × id milliseconds, so later ids finish faster than earlier ones. One after another, the calls would take 1,620 ms in total. The program counts how many calls run at the same time.

Java
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Gatherers;
import java.util.stream.IntStream;

public class MapConcurrent {

    static final AtomicInteger running = new AtomicInteger();
    static final AtomicInteger peak = new AtomicInteger();

    // Simulates a remote call; slower for smaller ids so they finish out of order
    static String fetch(int id) {
        int now = running.incrementAndGet();
        peak.accumulateAndGet(now, Math::max);
        try {
            Thread.sleep(200 - id * 10L);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            running.decrementAndGet();
        }
        return "item-" + id;
    }

    public static void main(String[] args) {
        long start = System.nanoTime();
        List<String> results = IntStream.rangeClosed(1, 12).boxed()
                .gather(Gatherers.mapConcurrent(4, MapConcurrent::fetch))   // at most 4 at once
                .toList();
        long ms = (System.nanoTime() - start) / 1000000;

        System.out.println(results);
        System.out.println("peak concurrent calls: " + peak.get());
        System.out.println("faster than 12 sequential calls (1620 ms): " + (ms < 1620));
    }
}

Output:

Output
[item-1, item-2, item-3, item-4, item-5, item-6, item-7, item-8, item-9, item-10, item-11, item-12]
peak concurrent calls: 4
faster than 12 sequential calls (1620 ms): true

Although the higher ids finished their calls first, the results come out as item-1 to item-12 in order. No more than 4 calls ever ran at once, and the whole stream finished faster than the 1,620 ms that sequential calls would need. With four calls overlapping, the expected time is roughly a quarter of that. Unlike parallel(), which uses the common fork-join pool sized to the CPU count, mapConcurrent lets you set the limit to what the remote service can take.

Writing your own gatherer

A gatherer is built from up to four functions. The most important are the first two:

  • initializer creates the state object, once per stream;
  • integrator is called for each element with the state, the element and a downstream. It calls downstream.push(x) to emit elements, and returns false to stop processing.
  • combiner merges state for parallel streams, and finisher can emit final elements at the end. Both are optional.

Gatherer.ofSequential builds a gatherer that is always run in order. The two gatherers below show state and short-circuiting:

  • distinctBy keeps a set of keys already seen and passes on only the first element for each key. Integrator.ofGreedy tells the stream that this integrator never stops early by itself, which allows some optimizations.
  • whileIncreasing remembers the last value and returns false at the first element that is not larger.
Java
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Gatherer;
import java.util.stream.Stream;

public class CustomGatherers {

    // Keep the first element for each key: like distinct(), but by a property
    static <T, K> Gatherer<T, ?, T> distinctBy(Function<? super T, ? extends K> key) {
        return Gatherer.ofSequential(
                () -> new HashSet<K>(),                                  // initializer: state
                Gatherer.Integrator.<Set<K>, T, T>ofGreedy((seen, element, downstream) -> {
                    if (seen.add(key.apply(element))) {
                        return downstream.push(element);
                    }
                    return true;                                         // keep going
                }));
    }

    // Pass elements while each is larger than the previous one, then stop the stream
    static Gatherer<Integer, ?, Integer> whileIncreasing() {
        class Last {
            Integer value;
        }
        return Gatherer.ofSequential(
                Last::new,
                (last, element, downstream) -> {
                    if (last.value != null && element <= last.value) {
                        return false;                                    // short-circuit
                    }
                    last.value = element;
                    return downstream.push(element);
                });
    }

    record Person(String name, String city) {
    }

    public static void main(String[] args) {
        List<Person> people = List.of(new Person("Ana", "Oslo"), new Person("Ben", "Rome"),
                new Person("Cy", "Oslo"), new Person("Di", "Lima"), new Person("Ed", "Rome"));
        System.out.println("first person per city: "
                + people.stream().gather(distinctBy(Person::city)).map(Person::name).toList());

        System.out.println("while increasing: "
                + Stream.of(1, 3, 4, 9, 2, 10, 11).gather(whileIncreasing()).toList());

        // Short-circuiting means an infinite stream is fine
        System.out.println("from an infinite stream: "
                + Stream.iterate(1, n -> n < 1000 ? n * 2 : 1).gather(whileIncreasing()).toList());
    }
}

Output:

Output
first person per city: [Ana, Ben, Di]
while increasing: [1, 3, 4, 9]
from an infinite stream: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
  • Ana and Cy both live in Oslo, and Ben and Ed in Rome; only the first of each pair is kept.
  • The second stream stops at 2 because it is smaller than 9, so 10 and 11 are never examined, even though they are larger again. That is the difference from filter.
  • The infinite stream doubles until it passes 1000 and then wraps around to 1. The gatherer stops there, so the stream ends after 1024 instead of running forever.

Finishers and composition: run-length encoding

Some operations can only emit their last result at the end of the stream. Run-length encoding is a good test: a run is emitted when the value changes, so the final run, which never sees a change, must be pushed by the finisher. The log ends with two "warn" entries to make the difference visible.

Java
import java.util.List;
import java.util.stream.Gatherer;
import java.util.stream.Gatherers;
import java.util.stream.Stream;

public class FinisherAndCompose {

    record Run(String value, int count) {
    }

    static final class State {
        String value;
        int count;
    }

    // Run-length encoding: push a run when the value changes
    static final Gatherer.Integrator<State, String, Run> PUSH_ON_CHANGE =
            Gatherer.Integrator.ofGreedy((state, element, downstream) -> {
                if (state.count > 0 && !element.equals(state.value)) {
                    downstream.push(new Run(state.value, state.count));
                    state.count = 0;
                }
                state.value = element;
                state.count++;
                return true;
            });

    // The last run never sees a change, so only the finisher can emit it
    static Gatherer<String, ?, Run> runs() {
        return Gatherer.ofSequential(State::new, PUSH_ON_CHANGE, (state, downstream) -> {
            if (state.count > 0) {
                downstream.push(new Run(state.value, state.count));
            }
        });
    }

    static Gatherer<String, ?, Run> runsWithoutFinisher() {
        return Gatherer.ofSequential(State::new, PUSH_ON_CHANGE);
    }

    public static void main(String[] args) {
        List<String> log = List.of("ok", "ok", "ok", "err", "err", "ok", "warn", "warn");
        System.out.println("runs:                 " + log.stream().gather(runs()).toList());
        System.out.println("runs, no finisher:    "
                + log.stream().gather(runsWithoutFinisher()).toList());

        // andThen composes two gatherers into one
        Gatherer<String, ?, List<Run>> runsInPairs = runs().andThen(Gatherers.windowFixed(2));
        System.out.println("runs, then pairs:     " + log.stream().gather(runsInPairs).toList());

        // Gatherers chain like any intermediate operation
        System.out.println("long runs only:       " + Stream.of("a", "a", "b", "c", "c", "c")
                .gather(runs()).filter(r -> r.count() > 1).map(Run::value).toList());
    }
}

Output:

Output
runs:                 [Run[value=ok, count=3], Run[value=err, count=2], Run[value=ok, count=1], Run[value=warn, count=2]]
runs, no finisher:    [Run[value=ok, count=3], Run[value=err, count=2], Run[value=ok, count=1]]
runs, then pairs:     [[Run[value=ok, count=3], Run[value=err, count=2]], [Run[value=ok, count=1], Run[value=warn, count=2]]]
long runs only:       [a, c]
  • With the finisher, the log of 8 entries became 4 runs: ok × 3, err × 2, ok × 1 and warn × 2. The second "ok" run is separate because runs are consecutive, unlike grouping.
  • Without the finisher, the same integrator lost warn × 2. This is the most common bug in hand-written gatherers that buffer elements.
  • runs().andThen(Gatherers.windowFixed(2)) composed two gatherers into one, giving the 4 runs in pairs.
  • A gatherer is followed by ordinary operations: filter kept the runs longer than 1, "a" and "c".
  • The state is created by State::new for each evaluation. Keeping state in fields captured by the lambda instead would share it between every stream that uses the gatherer, which breaks as soon as it is used twice.

Laziness, collectors and parallel streams

The program counts how many source elements each approach pulls, using an infinite stream for the gatherer and a 1,000-element stream for the collector, and then runs a sequential gatherer on a parallel stream.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Gatherers;
import java.util.stream.Stream;

public class Laziness {

    public static void main(String[] args) {
        // A gatherer pulls only as many elements as the rest of the pipeline needs
        List<Integer> pulled = new ArrayList<>();
        List<List<Integer>> firstTwo = Stream.iterate(1, n -> n + 1)      // infinite
                .peek(pulled::add)
                .gather(Gatherers.windowFixed(3))
                .limit(2)
                .toList();
        System.out.println("windows: " + firstTwo + ", elements pulled: " + pulled.size());

        // Chunking with a collector must read the whole (finite) stream first
        pulled.clear();
        List<List<Integer>> chunks = Stream.iterate(1, n -> n <= 1000, n -> n + 1)
                .peek(pulled::add)
                .collect(Collectors.collectingAndThen(Collectors.toList(), all -> {
                    List<List<Integer>> out = new ArrayList<>();
                    for (int i = 0; i < all.size(); i += 3) {
                        out.add(all.subList(i, Math.min(i + 3, all.size())));
                    }
                    return out;
                }))
                .subList(0, 2);
        System.out.println("chunks:  " + chunks + ", elements pulled: " + pulled.size());

        // scan and fold are sequential: the order of a parallel stream is kept
        List<Integer> parallelScan = Stream.of(1, 2, 3, 4, 5).parallel()
                .gather(Gatherers.scan(() -> 0, Integer::sum)).toList();
        System.out.println("scan on a parallel stream: " + parallelScan);
    }
}

Output:

Output
windows: [[1, 2, 3], [4, 5, 6]], elements pulled: 6
chunks:  [[1, 2, 3], [4, 5, 6]], elements pulled: 1000
scan on a parallel stream: [1, 3, 6, 10, 15]
  • windowFixed(3) followed by limit(2) pulled exactly 6 elements from an infinite stream: two windows of three.
  • Chunking with a collector gave the same two chunks, but pulled all 1,000 elements first, and it would never finish on an infinite stream. Before Java 24 this was the usual way to batch a stream.
  • scan has no combiner, so on a parallel stream it still produced the running sums 1, 3, 6, 10, 15 in order. Gatherers without a combiner are evaluated sequentially; other stages of the pipeline can still run in parallel.

What a gatherer costs

The program doubles five million integers and sums them three ways: a plain loop, a boxed stream with map, and the same stream with a gatherer doing the doubling. Each runs 3 times after a warm-up round and the fastest is shown. This is a rough comparison on a 2-CPU Linux machine with JDK 25.

Java
import java.util.stream.Gatherer;
import java.util.stream.IntStream;

public class GatherCost {

    interface Work {
        long run();
    }

    public static void main(String[] args) {
        Gatherer<Integer, ?, Integer> doubling = Gatherer.of(
                Gatherer.Integrator.ofGreedy((_, x, downstream) -> downstream.push(x * 2)));
        int n = 5000000;
        for (int round = 0; round < 2; round++) {           // round 0 is warm-up
            boolean print = round == 1;
            time("for loop", print, () -> {
                long s = 0;
                for (int i = 0; i < n; i++) {
                    s += i * 2;
                }
                return s;
            });
            time("boxed map(x * 2)", print, () -> IntStream.range(0, n).boxed()
                    .map(x -> x * 2).mapToLong(Integer::longValue).sum());
            time("boxed gather(doubling)", print, () -> IntStream.range(0, n).boxed()
                    .gather(doubling).mapToLong(Integer::longValue).sum());
        }
    }

    static void time(String label, boolean print, Work w) {
        long best = Long.MAX_VALUE;
        long result = 0;
        for (int i = 0; i < 3; i++) {
            long t0 = System.nanoTime();
            result = w.run();
            best = Math.min(best, System.nanoTime() - t0);
        }
        if (print) {
            System.out.printf("%-24s sum %,d  best of 3: %,4d ms%n", label, result,
                    best / 1000000);
        }
    }
}

Output:

Output
for loop                 sum 24,999,995,000,000  best of 3:    1 ms
boxed map(x * 2)         sum 24,999,995,000,000  best of 3:   16 ms
boxed gather(doubling)   sum 24,999,995,000,000  best of 3:   13 ms
  • The gatherer and map took about the same time; across runs either one can come out a few milliseconds ahead. The pipeline machinery is the same, with one call per element through the integrator.
  • Both boxed streams were more than ten times slower than the loop, mostly because of boxing every int. The gatherer does not change that; Stream.gather exists only on object streams, not on IntStream.
  • Use a built-in operation when one exists and a gatherer when the logic needs state or early stopping. For CPU-bound loops over primitives, a plain loop or IntStream stays fastest.

Which one to use

Choosing an operation
NeedUse
Batches of n elementsGatherers.windowFixed(n)
Moving averages, pairs of neighboursGatherers.windowSliding(n)
Running totals, one output per inputGatherers.scan
One result, but as part of a longer pipelineGatherers.fold; otherwise a collector or reduce
Remote calls per element with a concurrency limitGatherers.mapConcurrent(n, f)
Distinct by a key, run-length encoding, stop on a conditionA custom gatherer with Gatherer.ofSequential
Stateless one-to-many mappingflatMap or mapMulti
Simple stop condition on each element alonetakeWhile

For the rest of the Stream API, see streams and advanced streams.