Phase 17 of 20 · Topic 17.1

Functional Interfaces & Built-in Functional Types

1Concept

A Functional Interface has exactly ONE abstract method (SAM - Single Abstract Method) and is marked with `@FunctionalInterface`. Key built-in types in `java.util.function`: 1. `Predicate<T>` (T -> boolean); 2. `Function<T, R>` (T -> R); 3. `Consumer<T>` (T -> void); 4. `Supplier<T>` (() -> T); 5. `UnaryOperator<T>` (T -> T).

2Architecture Diagram

+-------------------+-----------------------+-------------------------+
| Interface         | Method Signature      | Common Use Case         |
+-------------------+-----------------------+-------------------------+
| Predicate<T>      | boolean test(T t)     | Filtering data          |
| Function<T, R>    | R apply(T t)          | Transforming data       |
| Consumer<T>       | void accept(T t)      | Processing / Printing   |
| Supplier<T>       | T get()               | Factory object creation |
+-------------------+-----------------------+-------------------------+

3Code Example

Core Java
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class FunctionalInterfacesDemo {
    public static void main(String[] args) {
        Predicate<Integer> isEligible = score -> score >= 75;
        Function<String, Integer> lengthMapper = String::length;
        Consumer<String> logger = msg -> System.out.println("[AUDIT] " + msg);
        Supplier<Double> randomGenerator = Math::random;

        System.out.println("Predicate check (82): " + isEligible.test(82));
        System.out.println("Function transform: " + lengthMapper.apply("Enterprise Java"));
        logger.accept("Service initialized successfully.");
        System.out.printf("Supplier value: %.4f%n", randomGenerator.get());
    }
}

4Expected Output

Predicate check (82): true
Function transform: 15
[AUDIT] Service initialized successfully.
Supplier value: 0.7492

5Key Takeaways

  • Use primitive specializations (`IntPredicate`, `DoubleFunction`) to avoid autoboxing overhead.
  • Functional interfaces can contain multiple `default` or `static` methods without violating SAM rule.
  • Lambdas compile to `invokedynamic` instructions, NOT anonymous inner classes.