A lambda expression is a concise way to represent a function (a block of code) as an object. Introduced in Java 8, lambdas enable functional programming, allowing you to pass behavior as data.
They work only with Functional Interfaces (interfaces with exactly one abstract method).
- Cleaner, shorter code (no need for anonymous classes)
- Functional programming support
- Used extensively in Streams API
- Improves readability
- Ideal for passing small functions
(parameters) -> expression
(parameters) -> { statements }Examples:
() -> System.out.println("Hello")
(x) -> x * x
(a, b) -> a + bRunnable r = new Runnable() {
public void run() {
System.out.println("Running");
}
};Runnable r = () -> System.out.println("Running");Cleaner and shorter.
(int x, int y) -> x + y- Parameters:
(int x, int y) - Arrow token:
-> - Body:
x + y
If type can be inferred → omit type:
(x, y) -> x + yIf single parameter → parentheses optional:
x -> x * 10@FunctionalInterface
interface Operation {
int compute(int a, int b);
}Usage:
Operation add = (a, b) -> a + b;
System.out.println(add.compute(5, 3)); // 8Runnable r = () -> System.out.println("Hello");Consumer<String> c = s -> System.out.println(s);BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;(x, y) -> {
int z = x + y;
return z;
}Java provides many ready-made functional interfaces in java.util.function.
Predicate<Integer> isEven = x -> x % 2 == 0;
System.out.println(isEven.test(10)); // trueFunction<String, Integer> len = s -> s.length();Consumer<String> c = s -> System.out.println(s);Supplier<Double> random = () -> Math.random();Comparator<Integer> comp = (a, b) -> a - b;List<Integer> list = Arrays.asList(5, 2, 8, 1);
list.sort((a, b) -> a - b);List<Integer> nums = Arrays.asList(1,2,3,4,5);
nums.stream()
.filter(n -> n % 2 == 0)
.forEach(n -> System.out.println(n));Output:
2
4
Lambdas can use variables from outside if they are effectively final.
int x = 10;
Runnable r = () -> System.out.println(x);You cannot modify x after this.
Sometimes lambda just calls a method:
list.forEach(s -> System.out.println(s));Can be replaced with:
list.forEach(System.out::println);- Cannot modify effectively-final local variables
- No checked exceptions unless handled
- Cannot create standalone functions (Java is not purely functional)
- Only works with functional interfaces
A short block of code that implements a functional interface.
Yes, lambdas are objects implementing a functional interface.
Because JVM knows they provide only one method to implement.
Variables whose value does not change after assignment.
Yes, fewer anonymous class objects → faster invocation.
-
Lambda expressions implement functional interfaces.
-
They simplify anonymous classes.
-
Essential for Streams API and modern Java.
-
Support cleaner, functional-style programming.
-
Variables used must be effectively final.