Boris Spider is right: you can skip a stream only once, so you need Supplier<Stream<Thing>>
or need a collection.
<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);
}
Call examples:
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);
source
share