Search code examples
javajava-streamjava-9

Java 9 Stream iterate method ignores the last element of the stream


Regarding the Java 9 Stream iterate method, I am unsure about the order of execution of the Predicate and UnaryOperator methods.

Consider the following example:

Stream<BigInteger> streamIterate = Stream.iterate(BigInteger.ZERO, n -> n.intValue() < 100, n -> n.add(BigInteger.ONE));
streamIterate.forEach(System.out::println);

The values being printed go from 0 to 99 and this is what confused me.

If the first stream element is seed, and all the other elements are being added if the condition is satisfied for the current element, that means that when we add value of 99 to the stream it becomes the current element, the hasNext condition is satisfied and we should expect to have 100 as the last value, before the stream ends.

However, the stream ends with 99.


Solution

  • The predicate that you have will only allow upto and including 99 to be printed. Stream.iterate(BigInteger.ZERO, n -> n.intValue() < 100, n -> n.add(BigInteger.ONE)) is equivalent to, for (BigInteger n = BigInteger.ZERO; n.intValue() < 100; n.add(BigInteger.ONE)).

    Here is a simpler example, from Baeldung,

    Stream.iterate(0, i -> i < 10, i -> i + 1)
      .forEach(System.out::println);
    

    is equivalent to,

    for (int i = 0; i < 10; ++i) {
        System.out.println(i);
    }
    

    which would only print, 0 through 9.