Because this lambda expression invokes an existing method, you can use a method reference instead of a lambda expression:
[https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html, 8th Aug 2021]
package j8.in.janisoftwares;
import java.util.stream.*;
public class StreamExample {
public static void main(String[] args) {
Stream.iterate(1, e -> e + 1)
.filter(e -> e %5 == 0)
.limit(10)
.forEach(e -> System.out.println(e));
}
}
5 10 15 20 25 30 35 40 45 50
package j8.in.janisoftwares;
import java.util.stream.*;
public class MethodReferenceExample {
public static void main(String[] args) {
Stream.iterate(1, e -> e + 1)
.filter(e -> e %5 == 0)
.limit(10)
.forEach(System.out::println);
}
}
5 10 15 20 25 30 35 40 45 50
In Java8 we can use the method as if they were objects or primitive values, and we can treat them as a variable. The example shows the function as a variable in java
[https://www.geeksforgeeks.org/method-references-in-java-with-examples/, 8th Aug 2021]
Before Java 8, we could pass only 3 things in methods, namely:
- Primitive data type(s).
- Object references.
- Method invocation itself.
After Java 8, we can pass 1 more argument. i.e. Method Reference.
We can pass 4 types of Method references as argument in Java method.
- Static Method Reference.
- Instance Method Reference (of a particular object).
- Instance Method Reference (of an arbitrary object of a particular type).
- Constructor Reference.