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.
(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.
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));
}
}7The 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.
