Ryan Leach
Ryan Leach

Reputation: 4470

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?

Upvotes: 4

Views: 1837

Answers (3)

Ryan Leach
Ryan Leach

Reputation: 4470

If you have a finite Stream, and know that it fits in memory, you can use a intermediate collection.

final Stream<Thing> finiteStream = ???;
final List<Thing> finiteCollection = finiteStream.collect(Collectors.toList());
final Stream<Thing> infiniteThings = Stream.generate(finiteCollection::stream).flatMap(Functions.identity());

Upvotes: 1

Ryan Leach
Ryan Leach

Reputation: 4470

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.

Upvotes: 2

VGR
VGR

Reputation: 44308

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);

Upvotes: 6

Related Questions