Lambda Expressions
Lambda expressions were added in Java 8. They provide a clear and concise way to represent one method interface using an expression. They enable Functional Programming in Java.
Syntax
The simplest lambda expression contains a single parameter and an expression:
parameter -> expression
For more parameters or complex logic:
(param1, param2) -> {
// code block
return something;
}
Functional Interface
A Lambda expression can be used wherever the type is a Functional Interface. A functional interface is an interface with only one abstract method.
Common examples: Runnable, Comparator,
ActionListener.
Before Java 8 (Anonymous Class)
Runnable r = new Runnable() {
public void run() {
System.out.println("Running...");
}
};
After Java 8 (Lambda)
Runnable r = () -> System.out.println("Running...");
Full Example
Click Run to execute your code
Summary
- Lambdas make code more concise and readable.
- They remove the boilerplate of Anonymous Inner Classes.
- Syntax:
(parameters) -> { body }.
Enjoying these tutorials?