如何从 Java 8 中的有限流构建无限重复流?

Rya*_*ach 3 java java-stream

如何将有限的事Stream<Thing>物流变成无限重复的事物流?

VGR*_*VGR 5

Boris the Spider 是对的:一个 Stream 只能被遍历一次,所以你需要一个Supplier<Stream<Thing>>或你需要一个集合。

<T> Stream<T> repeat(Supplier<Stream<T>> stream) {
    return Stream.generate(stream).flatMap(s -> s);
}

<T> Stream<T> repeat(Collection<T> collection) {
    return Stream.generate(() -> collection.stream()).flatMap(s -> s);
}
Run Code Online (Sandbox Code Playgroud)

示例调用:

Supplier<Stream<Thing>> stream = () ->
    Stream.of(new Thing(1), new Thing(2), new Thing(3));

Stream<Thing> infinite = repeat(stream);
infinite.limit(50).forEachOrdered(System.out::println);

System.out.println();

Collection<Thing> things =
    Arrays.asList(new Thing(1), new Thing(2), new Thing(3));

Stream<Thing> infinite2 = repeat(things);
infinite2.limit(50).forEachOrdered(System.out::println);
Run Code Online (Sandbox Code Playgroud)