如何在Java 8中从有限流构建无限重复流?
如何将有限的物流Stream
变成无限重复的物流?
Boris the Spider是对的:Stream只能遍历一次,所以你需要一个Supplier
或者你需要一个Collection。
Stream repeat(Supplier> stream) { return Stream.generate(stream).flatMap(s -> s); } Stream repeat(Collection collection) { return Stream.generate(() -> collection.stream()).flatMap(s -> s); }
示例调用:
Supplier> stream = () -> Stream.of(new Thing(1), new Thing(2), new Thing(3)); Stream infinite = repeat(stream); infinite.limit(50).forEachOrdered(System.out::println); System.out.println(); Collection things = Arrays.asList(new Thing(1), new Thing(2), new Thing(3)); Stream infinite2 = repeat(things); infinite2.limit(50).forEachOrdered(System.out::println);
如果您有方便的番石榴和collections品,您可以执行以下操作。
final Collection thingCollection = ???; final Iterable cycle = Iterables.cycle(thingCollection); final Stream things = Streams.stream(cycle);
但是如果你有一个Stream而不是一个Collection,这没有任何帮助。
如果你有一个有限的Stream,并且知道它适合内存,你可以使用一个中间集合。
final Stream finiteStream = ???; final List finiteCollection = finiteStream.collect(Collectors.toList()); final Stream infiniteThings = Stream.generate(finiteCollection::stream).flatMap(Functions.identity());