Lambda expressions were introduced in Java 8 as a way to add functional programming features into the language.
Syntax
The syntax of a lambda expression consists of:
- A comma-separated list of parameters in parentheses
- The arrow token (
->
) - A body, which can be a single expression or a statement block between curly braces
{
}
.
- Lambda expressions are essentially anonymous functions (methods without a name) that implement a functional interface.
- A functional interface is an interface with a single abstract method.
Example of a functional interface:
Comparing Anonymous Classes vs. Lambda Approaches
We are going to look at two examples of using traditional anonymous classes inside a method versus creating lambda expression.
Example 1: Simple Calculator
Traditional Approach with Anonymous Classes
Before Java 8, if we wanted to implement a functional interface (an interface with just one abstract method), we have to create an anonymous inner class. This traditional approach was verbose and required a lot of boilerplate code.
TraditionalCalculator.java
|
|
Lambda Expression Approach
LambdaCalculator.java
Example 2: Creating Threads
Traditional Thread with Anonymous Class
TraditionalThread.java
|
|
Thread with Lambda Expression
LambdaThread.java
Lambda Expression Body
Lambda expressions can have different forms of bodies with or without a return
statement and curly braces.
Benefits of Lambda Expressions
- Less code: More concise and clear code
- Less repetition: Reduced boilerplate code (repetitive and often lengthy code).
- Functional programming: Enhanced support for functional programming.