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

一个人想着一个人 提交于 2019-12-08 00:13:19

问题


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


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/48119039/how-do-you-build-an-infinite-repeating-stream-from-a-finite-stream-in-java-8

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