Lambdas & Functional Interfaces
What is a lambda?
A lambda is a short, unnamed function you can pass around like a value.
// Old way: anonymous class
Comparator<String> byLength = new Comparator<String>() {
public int compare(String a, String b) { return a.length() - b.length(); }
};
// Lambda way ✨
Comparator<String> byLength = (a, b) -> a.length() - b.length();
Lambda syntax
| Form | Example |
|---|---|
| No parameters | () -> System.out.println("Hi") |
| One parameter | x -> x * 2 |
| Several parameters | (a, b) -> a + b |
| Multi-line body | (a, b) -> { int s = a + b; return s; } |
Functional interfaces
A lambda needs a target: an interface with exactly one abstract method. Mark it with @FunctionalInterface to let the compiler check.
Built-in ones in java.util.function:
| Interface | Takes → Returns | Example |
|---|---|---|
Predicate<T> | T → boolean | n -> n > 0 |
Function<T, R> | T → R | s -> s.length() |
Consumer<T> | T → nothing | s -> System.out.println(s) |
Supplier<T> | nothing → T | () -> new Random().nextInt() |
BiFunction<T, U, R> | T, U → R | (a, b) -> a * b |
UnaryOperator<T> | T → T | s -> s.toUpperCase() |
Method references ::
A shortcut when a lambda just calls an existing method:
s -> System.out.println(s)→System.out::printlns -> s.toUpperCase()→String::toUpperCases -> Integer.parseInt(s)→Integer::parseInt() -> new ArrayList<>()→ArrayList::new
Capturing variables
Lambdas can use local variables from outside, but only if they're effectively final (never reassigned).
Example
import java.util.*;
import java.util.function.*;
public class LambdaLab {
public static void main(String[] args) {
List<String> langs = new ArrayList<>(List.of("Java", "Go", "Kotlin", "C"));
langs.removeIf(s -> s.length() < 2); // remove "C"
langs.sort(Comparator.comparing(String::length));
langs.forEach(System.out::println); // Go, Java, Kotlin
Predicate<Integer> isEven = n -> n % 2 == 0;
Function<Integer, Integer> square = n -> n * n;
System.out.println(isEven.test(4)); // true
System.out.println(square.andThen(n -> n + 1).apply(3)); // 10
}
}