Skip to main content

Stream Gatherers

Definition​

A gatherer (Java 24) is a custom step in a stream pipeline that can group, window or carry state between items, which the old map and filter could not do. Gatherers ships ready-made ones such as windowFixed and windowSliding.

Example code​

Grouping items into windows

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

class Demo {
public static void main(String[] args) {
List<List<Integer>> batches = Stream.of(1, 2, 3, 4, 5, 6, 7)
.gather(Gatherers.windowFixed(3)) // groups of 3
.toList();
System.out.println(batches);

List<List<Integer>> pairs = Stream.of(1, 2, 3, 4)
.gather(Gatherers.windowSliding(2)) // overlapping pairs
.toList();
System.out.println(pairs);
}
}

// Output:
// [[1, 2, 3], [4, 5, 6], [7]]
// [[1, 2], [2, 3], [3, 4]]

Finished this page? Track your progress (saved only in your browser).