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

谁都会走 提交于 2019-12-06 09:15:27

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);
Ryan The Leach

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 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());
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!