J.IV · Java 25 practice question

What does the following Java 25 program print using Gatherers.windowSliding?

import java.util.stream.*;

void main() {
    var windows = Stream.of(1, 2, 3, 4)
        .gather(Gatherers.windowSliding(3))
        .toList();
    IO.println(windows);
}
Choose one answer
Check answer and explanation

Correct answer: [[1, 2, 3], [2, 3, 4]]

Explanation

Gatherers.windowSliding(3) produces overlapping windows of size 3, dropping the least recent element and adding the next element for each subsequent window: [1, 2, 3] then [2, 3, 4].

Common trap

Non-overlapping chunks of size 3 with a remainder of [4] is the behavior of Gatherers.windowFixed(3), not windowSliding(3). Three windows of size 2 would be produced by windowSliding(2), not windowSliding(3).

Source: Java SE 25 API: Gatherers.windowSliding
Checked against the cited text on 2026-11-25.

Report an error in this question