Stream.gather()
Applies a custom intermediate operation to a stream, such as splitting it into groups of N.
Available since: Java 24
Syntax
default <R> Stream<R> gather(Gatherer<? super T, ?, R> gatherer)Parameters
| Parameter | Type | Description |
|---|---|---|
| gatherer | Gatherer<? super T, ?, R> | An intermediate operation, usually from the `Gatherers` class. |
Return value
Stream<R>A stream of the operation results.
Examples
Fixed-size batches and a sliding window:
void main() {
List<Integer> nums = List.of(1, 2, 3, 4, 5);
IO.println(nums.stream().gather(Gatherers.windowFixed(2)).toList());
IO.println(nums.stream().gather(Gatherers.windowSliding(3)).toList());
}Output:
[[1, 2], [3, 4], [5]]
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]Notes
Finalized in Java 24. Ready-made operations in the Gatherers class: windowFixed(), windowSliding(), fold(), scan(), mapConcurrent(). In a compact source file the class is available without an import, like the whole java.base module; in an ordinary class you need import java.util.stream.Gatherers;.
See also
- Stream.map() — Transforms every element of a stream.
- Stream.collect() — Gathers stream elements into a collection, a string or another structure.
- Stream.limit() — Truncates a stream to its first N elements.
In the tutorial
- Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.