Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Using a gatherer, write a pipeline that turns a stream of temperature readings into a stream of 5-reading moving averages. Then explain the parts of the Gatherer interface.

With the built-in sliding window it is one pipeline: readings.stream().gather(Gatherers.windowSliding(5)).map(w -> w.stream().mapToDouble(Double::doubleValue).average().orElseThrow()).toList(). A Gatherer itself has four parts: an initializer that creates per-stream state, an integrator that receives each element and may push results to the downstream, an optional combiner for parallel evaluation, and a finisher that runs at the end. The integrator can return false to stop early, Gatherer.ofSequential builds gatherers that never run in parallel, and gatherers can be chained with andThen.

Background to this question

Moving averages are a standard way to smooth noisy sensor data, latency measurements or prices. Before Java 24, computing one with streams meant collecting into a list and indexing into it, which defeats the purpose of a stream. Gatherers let us express it directly, and this question checks two things: that we know the built-in gatherer for the job, and that we understand the interface well enough to write our own when no built-in fits. In this answer, we will recap what a moving average is, write the pipeline with windowSliding, take apart the Gatherer interface piece by piece, write a more efficient custom version, and look at short-circuiting and chaining.

1A Quick Recap of Moving Averages

A 5-reading moving average replaces each position with the average of the last five readings. For readings 20, 21, 22, 23, 24, 25 the first average covers 20 to 24 and is 22.0; the window then moves one step and covers 21 to 25, giving 23.0. Each new reading pushes the oldest one out.

So the operation needs state that spans elements: the last five readings. That is exactly what map and filter cannot do, because they see one element at a time with no memory, and exactly what a gatherer can.

2The Pipeline With windowSliding

Gatherers.windowSliding(5) emits each overlapping window of five elements as a List. A map then turns each window into its average.

Java
List<Double> readings = List.of(20.0, 21.0, 22.0, 23.0, 24.0, 25.0);
List<Double> averages = readings.stream()
.gather(Gatherers.windowSliding(5)) // [20..24], [21..25]
.map(w -> w.stream().mapToDouble(Double::doubleValue).average().orElseThrow())
.toList();
System.out.println(averages); // [22.0, 23.0]

Notice orElseThrow after average. average() returns an OptionalDouble because an empty list has no average; our windows are never empty, so orElseThrow simply unwraps it. One edge case: if fewer than five readings arrive, windowSliding emits a single shorter window, so we would get one average of, say, three readings. If the business rule says no average until five readings exist, add filter(w -> w.size() == 5) before the map.

This version is clear and correct. Its cost is that each window is a new List and each average adds up five numbers again. For a few thousand readings that does not matter; for a high-rate sensor feed a custom gatherer that keeps a running sum is cheaper, and writing one shows how the interface works.

3The Parts of the Gatherer Interface

A Gatherer<T, A, R> takes input elements of type T, keeps private state of type A, and emits results of type R. It is defined by up to four functions, and the stream calls them at fixed moments.

Step throughHow the stream drives a gatherer
  1. initializer()create state, for example an empty window
  2. integrator(state, element, downstream)called for each element; may push results
  3. Did the integrator return false?
    YesStop sending elementsNoSend the next element
  4. combiner(left, right)only for parallel evaluation, if provided
  5. finisher(state, downstream)after the last element; flush leftovers

5 steps in order. Play them, or step through them one at a time.

Only the integrator is required; the others have defaults that do nothing.

The initializer, a Supplier<A>, creates fresh state when the stream starts, for example an empty deque. The integrator is called once per element with three arguments: the state, the element, and the downstream, an object whose push(r) method sends a result to the next stage. It returns a boolean: true means keep sending elements, false means this gatherer is done and the stream can stop. The combiner, a BinaryOperator<A>, merges two states when the stream runs in parallel; a gatherer without one runs sequentially. The finisher, a BiConsumer<A, Downstream>, is called after the last element and can push anything still held in the state, such as a final partial batch.

4Writing a Custom Moving Average Gatherer

Here is a gatherer that keeps the last n readings in a deque and a running sum, so each step costs one addition and one subtraction instead of summing the window again.

Java
static Gatherer<Double, ?, Double> movingAverage(int n) {
class Window {
final ArrayDeque<Double> values = new ArrayDeque<>(n);
double sum;
}
return Gatherer.<Double, Window, Double>ofSequential(
Window::new, // initializer
Gatherer.Integrator.ofGreedy((w, x, downstream) -> {
w.values.addLast(x);
w.sum += x;
if (w.values.size() > n) w.sum -= w.values.removeFirst();
if (w.values.size() < n) return true; // not enough readings yet
return downstream.push(w.sum / n); // false if downstream wants no more
}));
}
List<Double> averages = readings.stream().gather(movingAverage(5)).toList(); // [22.0, 23.0]

Notice the details. Gatherer.ofSequential takes an initializer and an integrator, and optionally a finisher; it has no combiner, so the gatherer never runs in parallel, which is right because a moving average depends on order. Integrator.ofGreedy marks an integrator that never stops early on its own, which lets the stream optimise slightly. We return the result of downstream.push, because push returns false when the next stage, for example a limit, wants no more elements; passing that on lets the whole pipeline stop. There is no finisher because a moving average has nothing to flush. A real implementation for very long streams of doubles would also guard against drift in the running sum, for example by recomputing it from the deque every so often.

5Stopping Early and Chaining With andThen

An integrator that returns false short-circuits the stream: no more elements are pulled from the source. That is how we could write a gatherer such as "take readings until the average exceeds 30", which emits averages and returns false once one crosses the threshold, so a sensor feed of millions of readings stops being read at that point.

Java
Gatherer<Double, ?, Double> smoothedThenCapped =
movingAverage(5).andThen(Gatherers.<Double, Double>scan(() -> 0.0, Math::max)); // running max of averages
List<Double> r = readings.stream().gather(smoothedThenCapped).toList(); // [22.0, 23.0]

andThen composes two gatherers into one, so the output of the first becomes the input of the second. It is equivalent to calling gather twice, but lets us name and reuse the combination, for example as a smoothing step shared across services.

6Follow-up questions

Why does Gatherer have three type parameters?

T is the type of elements coming in, R is the type going out, and A is the private state. Callers usually do not care about A, which is why we return Gatherer<Double, ?, Double> and keep the state class local to the factory method.

What is the difference between Gatherer.of and Gatherer.ofSequential?

Gatherer.of builds a gatherer that may run in parallel, and requires a combiner to merge states from different chunks. ofSequential builds one without a combiner, which always processes elements in order on one thread, even inside a parallel stream. Order-dependent operations such as moving averages belong in ofSequential.

Why is the state created by a Supplier instead of passed in directly?

Because a gatherer is a reusable description of an operation, and the same gatherer object may be used by many streams, possibly at the same time. The Supplier gives each evaluation its own fresh state, so two streams using movingAverage(5) never share a window.

7Conclusion

In this answer, we computed 5-reading moving averages with Gatherers.windowSliding(5) followed by a map that averages each window, and noted the partial window for short inputs. We then took the Gatherer interface apart: an initializer for state, an integrator that receives each element and pushes results downstream, an optional combiner for parallel use, and a finisher for leftovers. We wrote a cheaper custom version with Gatherer.ofSequential and a running sum, saw that returning false from the integrator stops the stream, and chained gatherers with andThen.

What to say in the interviewAbout 90 seconds aloud

Open with

The direct answer is readings.stream().gather(Gatherers.windowSliding(5)), which emits overlapping windows of five, then map each window to its average with mapToDouble and average().orElseThrow(), and toList. For 20 to 25 that gives 22.0 and 23.0.

Then, if they want more

One caveat: if there are fewer than five readings, windowSliding emits one shorter window, so I would filter on window size if the rule says five readings are required. As for the interface, a Gatherer of T, A, R has up to four parts. The initializer is a supplier that creates fresh state per evaluation.

The integrator is called for each element with the state, the element and a downstream; it can push zero or more results with downstream.push, and it returns a boolean, where false means stop, which is how gatherers short-circuit. The combiner merges states for parallel evaluation, and if there is none, the gatherer runs sequentially.

The finisher runs at the end to flush anything left, like a last partial batch. Gatherer.ofSequential builds one from an initializer and integrator with no combiner, which is what I would use for a custom moving average that keeps a deque and a running sum, so each step is one add and one subtract.

And gatherers compose with andThen, so I can package smoothing plus another step as one reusable gatherer.

About this answer

Last updated
12 November 2026
Versions it names
Java 24
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Using a gatherer, write a pipeline that turns a stream of temperature readings into a...": https://scrivio-interview-library.netlify.app/java/streams/769f611d1d/