Java / Java 21 Interview Questions
What are functional interfaces in Java and how are lambdas related to them?
A functional interface is an interface with exactly one abstract method (SAM β Single Abstract Method). The @FunctionalInterface annotation is optional but recommended β it causes the compiler to enforce the single-abstract-method rule. Lambdas and method references provide implementations for functional interfaces without requiring an anonymous class.
| Interface | Signature | Purpose |
|---|---|---|
| Function | R apply(T t) | Transform T to R |
| Consumer | void accept(T t) | Consume T, no return |
| Supplier | T get() | Produce T, no input |
| Predicate | boolean test(T t) | Test T β returns boolean |
| BiFunction | R apply(T t, U u) | Two inputs, one output |
| UnaryOperator | T apply(T t) | Function where T-in = T-out |
| BinaryOperator | T apply(T t1, T t2) | Two T inputs, one T output |
| Runnable | void run() | No input, no output |
| Callable | V call() | No input, returns V, throws Exception |
// Lambda syntax
Function length = s -> s.length();
Function length2 = String::length; // method reference
// Composing functions
Function toUpper = String::toUpperCase;
Function len = String::length;
Function upperLen = toUpper.andThen(len);
System.out.println(upperLen.apply("hello")); // 5
// Predicate composition
Predicate notBlank = Predicate.not(String::isBlank);
Predicate shortWord = s -> s.length() < 5;
Predicate both = notBlank.and(shortWord);
// Custom functional interface
@FunctionalInterface
interface ThrowingSupplier {
T get() throws Exception; // can declare checked exceptions
}
// Method reference types
String::toUpperCase // instance method β unbound
System.out::println // instance method β bound (specific object)
String::new // constructor reference
Integer::parseInt // static method reference
More Related questions...