Increment with the third argument of iterate method of Stream class added from Java9

Overview

This article summarizes the behavior when incrementing with the third argument of the iterate method of the Stream class added from Java9.

1. About the iterate method that has three input arguments of Stream class

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-)

2. Increment with third argument

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);

in conclusion

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

Increment with the third argument of iterate method of Stream class added from Java9
Find the address class and address type from the IP address with Java
[Java] Object-oriented syntax --class method / argument
[Java beginner] Conversion from character string to numerical value-What is the parseInt method of the Integer class? ~
Find the address class and address type from the IP address with Java [No. 2 decoction]
Let's express the result of analyzing Java bytecode with a class diagram
[Java Servlet] The road of Senri is also the third step from the first step
From Java9, the constructor of the class corresponding to primitive types is deprecated.
[Java] Get MimeType from the contents of the file with Apathce Tika [Kotlin]
[Java] Get the date with the LocalDateTime class
Part of the class called from the class under test in JMockit Mock method memo
[Java] Calculate the day of the week from the date (Calendar class is not used)
[Android] Call Kotlin's default argument method from Java
[Java] Handling of JavaBeans in the method chain
The order of Java method modifiers is fixed
[Java] Set the time from the browser with jsoup
Java method call from RPG (method call in own class)
Calculate the similarity score of strings with JAVA
Method name of static factory method learned from Java 8
First touch of the Files class (or Java 8)
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
Java General-purpose method that retrieves only the differences between the properties of objects of the same class
[Java] Sort ArrayList with elements of your own class
[Java] How to use compareTo method of Date class
CI the architecture of Java / Kotlin applications with ArchUnit
How to write Scala from the perspective of Java
Use Java lambda expressions outside of the Stream API
Call a method with a Kotlin callback block from Java
Java language from the perspective of Kotlin and C #
Monitor the internal state of Java programs with Kubernetes
Check the behavior of Java Intrinsic Locks with bpftrace
Java: Use Stream to sort the contents of the collection
The story of making dto, dao-like with java, sqlite
Summarize the additional elements of the Optional class in Java 9
Replace only part of the URL host with java
[Java] Coverage report could not be created with the combination of default method of Cobertura + interface
Java programming (class method)
How to get the class name / method name running in Java
Only the top level Stream can be parallelized with Java Stream.
Get to the abbreviations from 5 examples of iterating Java lists
[Java] Simplify the implementation of data history management with Reladomo
Java: The problem of which is faster, stream or loop
Summary of values returned by the Spliterator characteristics method #java
Be sure to compare the result of Java compareTo with 0
[Java] Delete the specified number of characters from the end of StringBuilder
Generate Stream from an array of primitive types in Java
[Java] Precautions when creating a process that calls a method of Abstract class using DI from a child class