← Chapter 7 — Input, Wrappers & Lambdas

29. Lambda Expressions

mixed

Description

A lambda expression is a compact way to provide behavior for a functional interface. A functional interface has exactly one abstract method.

Lambdas are common with collections, streams, and event handling. They work best when the action is short and has a descriptive surrounding context.

Subtopics

Lambda syntax

Description

Parameters are followed by an arrow and body.

Explanation

The target functional interface supplies the parameter and return types.

Example

Runnable task = () -> System.out.println("Study");

Functional interfaces

Description

They represent one operation.

Explanation

Runnable, Comparator, and Predicate are common examples.

Example

java.util.function.Predicate<Integer> pass = s -> s >= 40;

Explanation

A lambda can capture local variables only when they are final or effectively final. This restriction keeps behavior predictable.

Example

public class LambdaDemo {
    public static void main(String[] args) {
        Runnable reminder = () -> System.out.println("Aditi, review Java today!");
        reminder.run();
    }
}

Key points

  • Lambdas implement functional interfaces.
  • The arrow is written ->.
  • Runnable is a common functional interface.

Open reference