Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why using ++i but not i++ in lambda

Tags:

lambda

java-9

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(....)
like image 538
Tiina Avatar asked Mar 08 '23 11:03

Tiina


1 Answers

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.

like image 75
Adrian Shum Avatar answered Mar 29 '23 19:03

Adrian Shum