This article summarizes the behavior when incrementing with the third argument of the iterate method of the Stream class added from Java9.
As a usage of the iterate method that has three input arguments of Stream class, I often see it introduced in the following code.
Stream.Sample code for how to use iterate
//Code that outputs a numerical value from 0 to 9
Stream.iterate(0, i -> i < 10, i -> i + 1).forEach(System.out::println);
Execution result
0
1
2
3
4
5
6
7
8
9
The arguments of the iterate method are as follows. ** First argument **: Initial value ** Second argument **: Class that returns the condition for returning the next Stream element (described in a lambda expression in the sample code) ** Third argument **: Class that returns the element of the next Stream (described in a lambda expression in the sample code) If you rewrite it into the conventional for statement, it will be as follows.
Code that rewrites the sample code into the conventional for statement
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
When I first learned about it, I was impressed that the Stream API could be used for something like a for statement.
The Java API documentation is linked below. [Specifications of Stream.iterate from Java API document](https://docs.oracle.com/javase/jp/9/docs/api/java/util/stream/Stream.html#iterate-T-java.util .function.Predicate-java.util.function.UnaryOperator-)
I was wondering about the fact that the third argument is often explained by i-> i + 1 without using increment, so I wrote the following.
Code that rewrites the third argument of the sample code?
Stream.iterate(0, i -> i < 10, i -> i++).forEach(System.out::println);
Then, the execution result is as follows.
Execution result
0
0
0
0
0
0
0
0
~~~~~~~~~~~~~~~~~~~~~~
Below, 0 is output endlessly, so it is omitted.
~~~~~~~~~~~~~~~~~~~~~~
The result will be output with i = 0, and an infinite loop will occur. Since the apply method of the UnaryOperator class specified in the third argument in Stream.class (described in the lambda expression in the sample code) is used, it is returned before incrementing the value in the third argument. If you really want to increment it, you need to rewrite it from the suffix to the prefix as follows.
Code that rewrites the third argument of the sample code
Stream.iterate(0, i -> i < 10, i -> ++i).forEach(System.out::println);
Since there is such a feature about increment, it may be written in i-> i + 1 when introducing it. When writing personally, it seems to use increment. In the first place, I only use Java after 9 for myself ...
Recommended Posts