I happen to know that, in the following expression, using i++
would result in infinite stream, i
would be always 0. I am confused is because I think i++
returned value is not used, even so, it should not interrupt i
increment afterwards.
IntStream.iterate(0, i-> i<10, i-> ++i).forEach(....)
By checking the API of Java 9 IntStream
: http://download.java.net/java/jdk9/docs/api/java/util/stream/IntStream.html#iterate-int-java.util.function.IntPredicate-java.util.function.IntUnaryOperator-
The last function (i -> ++i
in your case) is to determine what's the next value.
If you put i->i++
, given it is a postfix increment operator, i++
evaluates to i
before increment. Which means it is always returning the same value (seed 0
in your case). Therefore it works just like you are putting i -> i
. Please note that arguments in Java is passed by value. Therefore your increment in the lambda is not going to affect caller.
Therefore, the hasNext
predicate (2nd argument, i->i<10
in your case) always evaluates to true, hence giving you an infinite stream of all zeros.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With