How can I turn a finite Stream of things Stream<Thing> into an infinite repeating stream of things?
Boris the Spider is right: a Stream can only be traversed once, so you need a Supplier<Stream<Thing>> or you 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);
}
Example invocations:
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);
If you have Guava and a Collection handy, you can do the following.
final Collection<Thing> thingCollection = ???;
final Iterable<Thing> cycle = Iterables.cycle(thingCollection);
final Stream<Thing> things = Streams.stream(cycle);
But this doesn't help if you have a Stream rather then a Collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With