Why use ++ i but not i ++ in lambda

It seems to me that in the following expression, the use i++

will result in an infinite stream, it i

will always be 0. I am confused that I think the return value is i++

not used, even if, it should not interrupt the i

increment afterwards.

IntStream.iterate(0, i-> i<10, i-> ++i).forEach(....)

      

+3


source to share


3 answers


Checking the Java 9 API 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 for determining the next value.



If you put i->i++

, if it is a postfix increment operator, i++

evaluates to i

before increment. This means it always returns the same value (seed 0

in your case). Therefore it works the same way as you place i -> i

. Note that arguments in Java are passed by value. Therefore your increment in lambda will not affect the caller.

Hence the predicate hasNext

(2nd argument, i->i<10

in your case) always evaluates to true, hence giving you an endless stream of all zeros.

+4


source


You can use the limit and do what you suggest:

IntStream.iterate(0, i -> i++).limit(10).forEach(....)

      



Also it might help:

Java incremental operator query (++ i and i ++)

+1


source


Remember that a lambda expression is a way of representing as an anonymous function an implementation of a functional interface (an interface that has only one abstract method).

In your iterate () method, the third argument is IntUnaryOperator. It has one abstract method, applyAsInt (), which takes an int as an argument and returns an int. If you rewrite the Lambda expression as an equivalent anonymous inner class (which you might well use here), you end up with:

IntStream.iterate(0, i -> i < 10, new IntUnaryOperator() {
  @Override
  public int applyAsInt(int i) {
    return i++;
  }
})
.forEach(System.out::println);

      

In this case, it is clear that you are returning the value i before incrementing it (postfix operator). The initial value of i is zero, so you end up with an endless stream of zeros. If you change the applyAsInt () method to use the prefix operator, ++ i, the value of i will be incremented before it is returned, giving the desired result 1, 2 ... 9

0


source







All Articles