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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
