Authors says that code will not terminate.
Yes, because this specific overload of iterate
static IntStream iterate(int seed,
IntUnaryOperator f)
Returns an infinite sequential ordered IntStream produced by iterative
application of a function f to an initial element seed, producing a
Stream consisting of seed, f(seed), f(f(seed)), etc.
returns an infinite stream and given it's an infinite stream it means it can only be terminated via certain operations.
Given the terminal operation in use here (forEach
) is not short-circuiting it means that you require a "short-circuiting intermediate operation" to truncate the infinite stream in this specific case e.g. limit
(JDK8),takeWhile
(JDK9) et al.
The only short-circuiting intermediate operation in JDK8 is limit
as it allows computations on infinite streams to complete in finite time.
The reason is that there’s no way to know in the filter that the
numbers continue to increase, so it keeps on filtering them
infinitely!
filter
itself is not a short-circuiting intermediate operation hence cannot terminate a stream. filter
's job is essentially to return a stream consisting of the elements of the stream that match the given predicate.
Conclusion: if one is using an infinite stream which does not have a short-circuiting terminal operation then it requires a short-circuiting intermediate operation to truncate the stream else the stream remains infinite.