How to Use Lambda Expression in Java: Syntax and Examples
In Java, a
lambda expression is a short block of code that takes parameters and returns a value, used mainly to implement functional interfaces. You write it using the syntax (parameters) -> expression or (parameters) -> { statements } to simplify code and enable functional programming.Syntax
A lambda expression in Java has this basic form:
- Parameters: The input values inside parentheses, e.g.,
(x, y). - Arrow token: The
->symbol separates parameters from the body. - Body: The code to execute, either a single expression or a block inside braces.
This syntax replaces anonymous classes for functional interfaces.
java
(parameters) -> expression
(parameters) -> { statements; }Example
This example shows how to use a lambda expression to implement a simple interface that adds two numbers.
java
import java.util.function.BinaryOperator; public class LambdaExample { public static void main(String[] args) { // Lambda expression to add two integers BinaryOperator<Integer> add = (a, b) -> a + b; int result = add.apply(5, 3); System.out.println("Sum: " + result); } }
Output
Sum: 8
Common Pitfalls
Common mistakes when using lambda expressions include:
- Not matching the functional interface method signature.
- Trying to use statements without braces when multiple lines are needed.
- Confusing variable scope inside lambdas.
Always ensure your lambda matches the expected interface method.
java
/* Wrong: multiple statements without braces */ // (a, b) -> System.out.println(a); System.out.println(b); // Error /* Correct: use braces for multiple statements */ (a, b) -> { System.out.println(a); System.out.println(b); }
Quick Reference
| Part | Description | Example |
|---|---|---|
| Parameters | Input values for the lambda | (x, y) |
| Arrow token | Separates parameters and body | -> |
| Body | Code to execute, expression or block | x + y or { return x + y; } |
| Functional Interface | Interface with one abstract method | Runnable, Comparator |
Key Takeaways
Lambda expressions simplify implementing functional interfaces with concise syntax.
Use parentheses for parameters and an arrow (->) before the body.
Use braces for multiple statements inside the lambda body.
Ensure the lambda matches the functional interface method signature.
Lambdas improve code readability and enable functional programming styles.