如何将有限的事物流Stream<Thing>转换为无限重复的事物流?
发布于 2018-01-06 02:50:14
蜘蛛鲍里斯是对的:一个流只能被遍历一次,所以你需要一个Supplier<Stream<Thing>>或者你需要一个集合。
<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);发布于 2018-01-06 02:56:48
如果你手头有一个Guava和一个Collection,你可以做以下事情。
final Collection<Thing> thingCollection = ???;
final Iterable<Thing> cycle = Iterables.cycle(thingCollection);
final Stream<Thing> things = Streams.stream(cycle);但是如果你有一个Stream而不是一个Collection,这不会有什么帮助。
发布于 2018-01-06 03:03:11
如果你有一个有限的流,并且知道它可以放在内存中,你可以使用一个中间集合。
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
复制相似问题