如何在Java 8中从有限流构建无限重复流?

时间:2018-01-05 18:07:52

标签: java java-stream

如何将有限的事物流Stream<Thing>变成无限重复的事物流?

3 个答案:

答案 0 :(得分:4)

Boris the Spider是对的:Stream只能遍历一次,所以你需要一个Supplier<Stream<Thing>>或者你需要一个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);
}

示例调用:

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

答案 1 :(得分:1)

如果您有方便的番石榴和收藏品,您可以执行以下操作。

final Collection<Thing> thingCollection = ???;
final Iterable<Thing> cycle = Iterables.cycle(thingCollection);
final Stream<Thing> things = Streams.stream(cycle);

但如果你有一个Stream而不是一个Collection,那么这无济于事。

答案 2 :(得分:1)

如果你有一个有限的Stream,并且知道它适合内存,你可以使用中间集合。

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