I am currently learning about Lambda expressions in Java. As per my understanding it is a block of code that we can pass around so that it can be executed later. But I cannot think of examples when we want to execute the code later.
What are various scenarios where this is useful? Also what is the connection between Lambda Expression and Functional interface?
A Lambda expression
is used when we want to execute a block of code later, once or multiple times. The actual point of using it is deferred execution
and there are many reasons for executing code later, such as:
Connection between Lambda Expression and Functional Interface
A Functional interface
is an interface which has only one abtract method (though it can have multiple default methods). We can supply a lambda expression whenever an object of an Functional Interafce is expected. Consider an example where we want to execute some action n times.
execute(n, () -> System.out.println("Java Rocks"));
To accept the lambda the second parameter of the method signature must be Functional Interface and in the above example we can use e.g Runnable.
public static void execute(int n, Runnable action) {
for(int counter = 0; counter < n; counter ++) {
action.run();
}
}
The point to note here is that the Lambda Expression is executed when action.run()
is called. You can read more about Lambda Expression here.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments