0
0
JavaHow-ToBeginner · 3 min read

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

PartDescriptionExample
ParametersInput values for the lambda(x, y)
Arrow tokenSeparates parameters and body->
BodyCode to execute, expression or blockx + y or { return x + y; }
Functional InterfaceInterface with one abstract methodRunnable, Comparator, etc.

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.