Lambda Expressions and Functional Interfaces
Site Admin
· 11 Sep 2026
· 10 views
Passing Behaviour as Data
A lambda expression is a compact block of code you can pass around like a value. It is the modern, readable replacement for anonymous classes that implemented a single method.
The Old Way vs Lambda
// Anonymous class
Runnable oldWay = new Runnable() {
@Override
public void run() {
System.out.println("Old style");
}
};
// Lambda
Runnable newWay = () -> System.out.println("Lambda style");Lambda Syntax Shapes
// no parameters
action() -> System.out.println("Hello");
// one parameter - parentheses optional
x -> x * 2;
// several parameters
(a, b) -> a + b;
// block body with return
(a, b) -> { int sum = a + b; return sum; };Functional Interfaces
A functional interface has exactly one abstract method - that is the contract the lambda satisfies. Java ships useful ones in java.util.function:
Function<T,R>- takes T, returns R.Predicate<T>- takes T, returns boolean.Consumer<T>- takes T, returns nothing.Supplier<T>- takes nothing, returns T.
import java.util.function.*;
Function<Integer, Integer> square = n -> n * n;
System.out.println(square.apply(5)); // 25
Predicate<String> longWord = w -> w.length() > 6;
System.out.println(longWord.test("elephant")); // trueCreating Your Own
interface Greeter {
String greet(String name);
}
Greeter casual = name -> "Hey " + name;
Greeter formal = name -> "Good day, " + name;
System.out.println(casual.greet("Riya"));Key Points
- Lambdas are compact implementations of single-method interfaces.
- Functional interfaces have exactly one abstract method.
- Use java.util.function interfaces for common shapes.