Lambda Expressions & Functional Interfaces
Prerequisites: Comparable & Comparator
A functional interface is any interface with exactly one abstract method — Java lets you implement one inline with a compact lambda expression instead of a full named class.
interface Greeter {
String greet(String name);
}
Greeter formal = name -> "Good day, " + name;
System.out.println(formal.greet("Ada")); // Good day, Ada
The standard library ships common functional interfaces ready to use, so you rarely need to declare your own:
import java.util.function.Function;
import java.util.function.Predicate;
Function<Integer, Integer> square = n -> n * n;
System.out.println(square.apply(5)); // 25
Predicate<String> isEmpty = String::isEmpty;
System.out.println(isEmpty.test("")); // true
String::isEmpty is a method reference — shorthand for a lambda
that just calls an existing method.
Common mistakes
- Writing
s -> s.isEmpty()whenString::isEmptysays the same thing more clearly — reach for a method reference whenever the lambda body is just "call this one existing method."