ReviseAlgo Logo

Modern Java Features

Stream Gatherers

Extend Stream pipelines with custom intermediate operations using Stream Gatherers.

Interview: Focuses on comparing custom collectors with gatherers, and using built-in gatherers (windowFixed, sliding).

Last Updated: June 13, 2026 10 min read

Introduced in Java 22, Stream Gatherers define a way to customize intermediate stream operations, allowing developers to manipulate data flows dynamically.

Core Idea

Stream Gatherers act as intermediate transformations, whereas Collectors represent terminal operations.

Why It Matters

Enables sliding windows or stateful filters inside streams without converting them to intermediate collections.

Interview Lens

Tests standard gatherers like windowFixed and implementing basic custom gatherer logic.

Built-in Gatherers

Java 22 provides several pre-configured gatherers:

  • Gatherers.windowFixed(size): Groups stream elements into fixed-size lists (batches).
  • Gatherers.windowSliding(size): Groups stream elements into sliding windows.
  • Gatherers.fold(initializer, accumulator): Stateful reduction mapping to a single value.

Code Walkthrough

This program demonstrates grouping stream elements into fixed-size windows.

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

public class StreamGathererDemo { public static void main(String[] args) { List> batches = Stream.of(1, 2, 3, 4, 5, 6, 7, 8) .gather(Gatherers.windowFixed(3)) // Groups elements in batches of 3 .toList();

System.out.println(batches); // [[1, 2, 3], [4, 5, 6], [7, 8]] } }

Interview-Relevant Information

Q: How do Gatherers differ from Collectors?
Answer: Collectors are terminal operations: they consume the stream and return a final result (like a List or Map), ending the pipeline. Gatherers are intermediate operations: they transform a stream into another stream, allowing you to chain additional filter, map, or gather calls afterward.

Quick Checklist

What is gather(windowFixed(size)) used for? Are gatherers intermediate or terminal operations? If yes, you understand Stream Gatherers.

Use Cases

Batching database records to optimize bulk inserts.

Analyzing sensor data streams using sliding averages.

Common Mistakes

Using custom collectors when an intermediate gatherer is needed to keep the stream pipeline open.

Assuming gatherers run on parallel streams without custom combiner implementations.