Lambda expression

A lambda expression is a concise way to write an anonymous function in Java. Introduced in Java 8, lambdas implement functional interfaces — interfaces with exactly one abstract method.

Syntax

// (parameters) -> expression   -- single-expression form
Runnable r = () -> System.out.println("running");
Comparator<String> byLen = (a, b) -> Integer.compare(a.length(), b.length());
Function<String, Integer> len = s -> s.length();

// (parameters) -> { block }   -- block form
Consumer<String> log = msg -> {
    System.out.println("[LOG] " + msg);
    logger.info(msg);
};

Lambda vs anonymous class

// Pre-Java 8 — anonymous class:
Runnable r1 = new Runnable() {
    @Override public void run() { System.out.println("running"); }
};

// Java 8+ — lambda (same behaviour):
Runnable r2 = () -> System.out.println("running");

Method references

When a lambda just calls an existing method, use a method reference:

list.forEach(s -> System.out.println(s));   // lambda
list.forEach(System.out::println);           // method reference — same thing

Capturing variables

Lambdas can capture effectively-final local variables from the enclosing scope:

int multiplier = 10;
Function<Integer, Integer> times = n -> n * multiplier;  // captures multiplier

Where lambdas shine

Stream pipelines (filter, map, reduce), event handlers (button.setOnAction(e -> …)), custom comparators, thread bodies.