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)