Nearby lessons
91 of 125Java - Functional Interfaces
- Lambda expressions — the big change
- Functional interfaces
- Default and static methods in interfaces
- The four workhorses: Predicate, Function, Consumer, Supplier
- Method references (::)
- The Stream API for processing collections
- Optional — safe null handling
- The new Date and Time API
Functional Interfaces is a core concept of the Java language. This lesson explains Functional Interfaces, The Four Functional Interfaces in java.util.function and Built-in Functional Interfaces — The Full List with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Functional Interfaces
A functional interface is an interface with exactly one abstract method. Because it has only one method, a lambda can implement it directly. We mark it with @FunctionalInterface.
The Four Functional Interfaces in java.util.function
Java 8 provides ready-made functional interfaces. These four cover almost everything:
| Interface | What it does | Method | Example |
|---|---|---|---|
| Predicate<T> | Tests a condition -> true/false | boolean test(T) | x -> x > 0 (is it positive?) |
| Function<T,R> | Converts T into R | R apply(T) | s -> s.length() (String -> int) |
| Consumer<T> | Does something, returns nothing | void accept(T) | x -> System.out.println(x) |
| Supplier<T> | Supplies/gives a value | T get() | () -> Math.random() |
Built-in Functional Interfaces — The Full List
Java already had several interfaces with exactly one abstract method — these are all functional interfaces you can use with lambdas:
| Interface | Single abstract method | Used for |
|---|---|---|
| Runnable | run() | Threads (already seen in Chapter 11) |
| Comparable<T> | compareTo(T) | Natural sorting (Chapter 15) |
| ActionListener | actionPerformed(ActionEvent) | GUI button clicks (Chapter 17) |
| Callable<T> | call() | Returning a value from a task |
| Comparator<T> | compare(T, T) | Custom sorting |
Plus the java.util.function package has Bi-variants for two parameters — BiFunction<T,U,R>, BiConsumer<T,U>, BiPredicate<T,U> — and primitive versions like IntFunction, LongSupplier for performance.
- Lambda = a function without a name; (params) -> logic.
- Functional interface = one abstract method, so a lambda can implement it.
- Interfaces now have default and static methods with bodies.
- Predicate (test), Function (apply), Consumer (accept), Supplier (get) are the four core functional interfaces.
- Method references (::) are shorthand for lambdas.
- Streams process collections with filter/map/sorted/collect pipelines.
- Optional prevents NullPointerException with orElse/isPresent.
- java.time (LocalDate, LocalDateTime) replaces the old Date/Calendar cleanly.