Lambda Expressions (introduced in Java 8) revolutionized Java by introducing Functional Programming capabilities. They allow you to treat functionality as a method argument, dramatically reducing boilerplate associated with anonymous inner classes.
// Old way: 6 lines of boilerplate for a simple click action
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("Thread running in background!");
}
};
// Modern Java 8+ Lambda: Clean, expressive, and concise
Runnable r2 = () -> System.out.println("Thread running in background!");
(parameter_list) -> { statement_body; }
(a, b). If only one parameter exists, parentheses can be omitted: x -> x * x.->): Separates parameter list from the execution body.return are omitted.::) OperatorWhen a lambda expression simply delegates to an existing method without extra logic, use Method References:
| Method Reference Type | Lambda Syntax | Method Reference (::) |
|---|---|---|
| Static Method | x -> Math.sqrt(x) |
Math::sqrt |
| Instance Method of Object | s -> System.out.println(s) |
System.out::println |
| Instance Method of Arbitrary Object | s -> s.toUpperCase() |
String::toUpperCase |
| Constructor Reference | () -> new ArrayList<>() |
ArrayList::new |
Lambda expressions require a Functional Interface target. Let us explore java.util.function: Predicate, Function, Consumer, and Supplier. Proceed to: Java Functional Interfaces →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Predicate, Function, Consumer.
Using lambdas in stream pipelines.
Writing lambda comparators.
Passing lambdas to Runnable.