Stream 的 SKIP 方法能否使无限流变得有限?

Can Stream's SKIP method making an infinite stream finite?

limit()skip() 方法使 Stream 更小。它们可以使有限流更小,或者它们 可以使有限流无限流。方法签名显示在此处:

Stream<T> limit(int maxSize)
Stream<T> skip(int n)

以下代码c....

以上摘自OCP java8本书。当它说“ 可以从无限流 中生成有限流”时,​​他们是同时使用还是单独使用这两种方法?我可以想象 limit() 如何使无限流变小,但 skip() 如何单独实现这一点?有没有办法或者文档中的措辞需要更清楚?

"could make a finite stream out of an infinite stream"肯定只适用于limit(),不适用于skip()

skip 就像从大海里拿了一杯水然后想 "how much water is left in the ocean?",而 limit 就像从大海里拿了一杯水然后想 "how much water did I take from the ocean?"

如果流是无限的,那么跳过一些元素仍然会留下无限流...

Stream.iterate(0L, i -> i + 1).skip(100).forEach(System.out::println);

理论上这将永远 运行。所以很可能这只是一个小错误,逃过了书评人的注意。

如果仔细查看 Java 文档,您会发现 limit(long maxSize) 提到它是一个 短路 操作。这意味着它可能不会在满足给定条件后立即退出源流的所有元素。因此,这可以将无限流更改为有限流。

Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.

This is a short-circuiting stateful intermediate operation.

另一方面,skip(long n) 方法没有这样的声明,所以基本上在跳过 n 个元素后,Stream 仍然可以是无限的:

Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned.

This is a stateful intermediate operation.

所以您正在阅读的书中关于 skip 方法的措辞不正确。