Stream Gatherers WindowFixed And Fold
Reshape streams with JDK 24 Gatherers: windowFixed batches elements into fixed-size lists and fold reduces a stream to a single accumulated value.
Code
import java.util.List;
import java.util.stream.Gatherers;
public class BatchWindows {
public static void main(String[] args) {
List<String> ids = List.of("a", "b", "c", "d", "e", "f", "g");
// windowFixed:把流切成定长批次,尾部不足也保留
List<List<String>> batches = ids.stream()
.gather(Gatherers.windowFixed(3))
.toList();
System.out.println("batches: " + batches);
// fold:流式累积出单一汇总值,没有中间集合
String joined = ids.stream()
.gather(Gatherers.fold(
() -> new StringBuilder(),
(sb, id) -> sb.append(id).append(',')))
.findFirst()
.orElse("");
System.out.println("folded: " + joined);
}
}What the code does
Stream Gatherers WindowFixed And Fold is built around the class BatchWindows and the function main.
The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.
Applying it
Output lines are prefixed (batches:, folded:), making each step’s effect easy to spot.
Statements that matter
List<List<String>> batches = ids.stream()
.gather(Gatherers.windowFixed(3))
.toList();
String joined = ids.stream()
.gather(Gatherers.fold(
() -> new StringBuilder(),
(sb, id) -> sb.append(id).append(',')))
.findFirst()
.orElse("");
FAQ
- What does Stream Gatherers WindowFixed And Fold print when run?
- Execute the whole file; each printed line is prefixed with a label like `batches:`, `folded:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.