流收集器

Java教程 2025-10-25

前言

JDK22引入了流收集器,也就是Gatherers关键字,该东西经过几次预览之后,在JDK24转正

流收集器使用

windowFixed方使用

public class GathererDemo {

    static void main() {
        List> fixedWindows = IntStream.range(0, 10).boxed()
                .gather(Gatherers.windowFixed(3))
                .toList();
        System.out.println( fixedWindows);
    }
}

输出结果为

image.png

windowSliding使用

public class Gatherer1Demo {

    public static void main() {
        List> list = Stream.iterate(0, i -> i + 1)
                .gather(Gatherers.windowSliding(2))
                .limit(5)
                .collect(Collectors.toList());
        System.out.println(list);
    }
}

输出结果为

image.png

总结

该特性在JDK24转正,可以放心使用,使用流处理器更好操作流