3

"The limit() and skip() methods make a Stream smaller. They could make a finite stream smaller, or they could make a finite stream out of an infinite stream. The method signatures are shown here:

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

The following code c...."

The above is an excerpt from OCP java 8 book. When it said "could make a finite stream out of an infinite stream", did they mean it in both the methods together or alone? I can imagine how limit() would make an infinite stream smaller, but how skip() alone would accomplish that? Is there a way or the wording in the documentation needs to be clearer?

4

2 回答 2

4

"could make a finite stream out of an infinite stream" is surely applicable to limit() only, not to to skip().

skip is like taking a cup of water from the ocean and wondering "how much water is left in the ocean?", whereas limit is like taking the same cup of water from it and wondering "how much water did I take from the ocean?"

If the stream is infinite, then skipping a number of elements will still leave you with an infinite stream...

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

This will theoretically run forever. So chances are it's just a minor inaccuracy that escaped the reviewer of the book.

于 2019-03-18T06:06:34.373 回答
2

If you look into the Java doc carefully you will see that for limit(long maxSize) it is mentioned that it is a short circuiting operation. That means it may not operate on all elements of the source stream as soon as the given criteria is satisfied it will exit. So this works in changing a infinite Stream to a finite one.

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.

The skip(long n) method on the other hand makes no such claims, so basically after skipping n elements the Stream could still be infinite:

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.

So the book you are reading has the wording incorrect about the skip method.

于 2019-03-18T06:07:05.927 回答