Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you build an infinite repeating stream from a finite stream in Java 8?

How can I turn a finite Stream of things Stream<Thing> into an infinite repeating stream of things?

like image 492
Ryan Leach Avatar asked Oct 26 '25 15:10

Ryan Leach


2 Answers

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);
like image 132
VGR Avatar answered Oct 29 '25 05:10

VGR


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.

like image 28
Ryan Leach Avatar answered Oct 29 '25 05:10

Ryan Leach