Java · Chapter 39 of 42

Java Lambda Expressions

A lambda expression is a concise way to represent an anonymous function — code that can be passed around like a value. Lambdas work with functional interfaces (interfaces with exactly one abstract method).

Lambdas greatly simplify code that uses interfaces like Runnable, Comparator, or custom functional interfaces, avoiding verbose anonymous class syntax.

Syntax
(a, b) -> a + b;
() -> System.out.println("run");

Lambda syntax

A lambda has the form `(parameters) -> expression` or `(parameters) -> { statements }`. Parameter types are usually inferred.

Functional interfaces

An interface with a single abstract method, like Runnable or Comparator, can be implemented directly using a lambda instead of a full class.

Example 1 (java)
import java.util.function.BiFunction;

public class Main {
  public static void main(String[] args) {
    BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
    System.out.println(add.apply(3, 4));
  }
}
Output
7

The lambda (a, b) -> a + b implements BiFunction's single abstract method concisely.

Key points

  • Lambdas provide a concise syntax for implementing functional interfaces.
  • A functional interface has exactly one abstract method.
  • Lambda parameter types are usually inferred.
  • Lambdas reduce boilerplate compared to anonymous classes.
💡 Note: @FunctionalInterface can be added to an interface to make the compiler enforce the single-abstract-method rule.

📝 Quick Quiz

1. What kind of interface can a lambda implement?

2. What symbol separates lambda parameters from its body?

3. What annotation helps enforce the single-method rule on an interface?