[英]How do you build an infinite repeating stream from a finite stream in Java 8?
如何將有限的事Stream<Thing>
轉換為無限重復的事物流?
蜘蛛鮑里斯(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);
如果您有番石榴和手提包,可以執行以下操作。
final Collection<Thing> thingCollection = ???;
final Iterable<Thing> cycle = Iterables.cycle(thingCollection);
final Stream<Thing> things = Streams.stream(cycle);
但是,如果您擁有一個Stream而不是一個Collection,這將無濟於事。
如果您有一個有限的Stream,並且知道它適合內存,則可以使用中間集合。
final Stream<Thing> finiteStream = ???;
final List<Thing> finiteCollection = finiteStream.collect(Collectors.toList());
final Stream<Thing> infiniteThings = Stream.generate(finiteCollection::stream).flatMap(Functions.identity());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.