Lambda Expression
A lambda expression is a short block of code that takes in parameters and returns a value. It's essentially an anonymous function—a function without a name—that can be passed around as if it were an object.
Lambda expressions are used to implement methods in functional interfaces (interfaces with a single abstract method).
Syntax: (parameters) -> expression
or (parameters) -> { statements; }
.
A simple lambda expression that takes two integers and returns their sum:
(int a, int b) -> a + b;
Factorial with a Block Lambda
A block lambda uses curly braces {}
and is necessary when the function body consists of more than one statement. It should explicitly return the value.
Program to calculate the factorial of a number using a block lambda.
// A functional interface with one abstract method
interface NumericFunction {
int calculate(int n);
}
Using this interface with a lambda expression.
public class FactorialLambda {
public static void main(String[] args) {
NumericFunction factorial = (n) -> {
int result = 1;
for (int i = 1; i <= n; i++) {
result = i * result;
}
return result; // Explicit return statement
};
int number = 5;
System.out.println("The factorial of " + number
+ " is " + factorial.calculate(number)); // Outputs 120
number = 7;
System.out.println("The factorial of "
+ number + " is " + factorial.calculate(number));
// Outputs 5040
}
}
How Lambdas Simplify the Code
Lambda expressions provide a much more concise syntax compared to the older method of using anonymous inner classes.
Before Lambdas (Anonymous Inner Class):
myButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Button was clicked!");
}
});
With a Lambda Expression:
myButton.setOnAction(event -> System.out.println("Button was clicked!"));
The lambda expression eliminates the need for the new EventHandler<>()
instantiation, the method declaration (public void handle(...)
), and the override annotation. It allows you to focus directly on the action to be performed, making the code shorter and much more readable.
Event Handler with a Lambda Expression
This JavaFX program creates a button. When clicked, it uses a lambda expression to print a message to the console.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
public class LambdaEventHandler extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Lambda Event Handler Demo");
Button myButton = new Button("Click Me!");
// Use a lambda expression for the event handler
myButton.setOnAction(event -> {
System.out.println("Button was clicked! Handled by a lambda.");
});
StackPane root = new StackPane(myButton);
Scene scene = new Scene(root, 300, 150);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}