Functional Interfaces & Lambdas
Functional interfaces, lambda expressions, method references, streams
- Understand functional interfaces and @FunctionalInterface
- Write concise code with lambda expressions
- Use built-in functional interfaces: Predicate, Function, Consumer, Supplier
- Apply method references for cleaner code
*Java Basics to Advanced | Interfaces Final Topic*
Table of Contents
- Definition and SAM
- The
@FunctionalInterfaceAnnotation - What is Allowed Inside a Functional Interface?
- Object Class Methods in Interfaces
- Way 1: Using
implementsKeyword - Way 2: Using Anonymous Class
- Way 3: Using Lambda Expression
- Comparison of All Three Ways
- Use Case 1: Functional Extending Non-Functional
- Use Case 2: Non-Functional Extending Functional
- Use Case 3: Functional Extending Functional
- Writing Your Own Functional Interface
- Summary Diagrams
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Quick Revision Summary
1. What is a Functional Interface?
1.1 Definition and SAM
Definition
A functional interface is an interface that contains exactly one abstract method.
That is the complete definition. One abstract method — nothing more, nothing less (for the abstract methods; other method types are allowed, as explained below).
SAM Single Abstract Method
Functional interfaces are also called SAM interfaces:
SAM = Single Abstract Method
The two terms are interchangeable:
- Functional interface — the Java 8 name
- SAM interface — the conceptual name emphasizing its defining characteristic
Why "Exactly One"?
This constraint — having exactly one abstract method — is what makes functional interfaces work with lambda expressions. When there is only one abstract method, Java knows which method a lambda is implementing without you having to name it. If there were two abstract methods, Java would not know which one the lambda applies to.
Basic Example
1// This IS a functional interface — one abstract method2public interface Bird {3 void canFly(String weather); // only one abstract method4}1// This is NOT a functional interface — two abstract methods2public interface Bird {3 void canFly(String weather);4 int getHeight(); // second abstract method → NOT functional5}1.2 The `@FunctionalInterface` Annotation
What It Does
The @FunctionalInterface annotation is an optional marker annotation that tells the compiler:
"This interface is intended to be a functional interface. Please enforce that it has exactly one abstract method."
1@FunctionalInterface2public interface Bird {3 void canFly(String weather); // ✅ one abstract method — OK4}1@FunctionalInterface2public interface Bird {3 void canFly(String weather);4 int getHeight(); // ❌ COMPILE ERROR: Multiple non-overriding abstract methods found5}Is It Mandatory?
No. @FunctionalInterface is completely optional.
An interface with exactly one abstract method is a functional interface whether or not the annotation is present:
1// Without annotation — STILL a functional interface2public interface Bird {3 void canFly(String weather); // one abstract method → functional interface4}The annotation's only purpose is to enforce the constraint at compile time and to document intent for other developers.
| Scenario | Is it a Functional Interface? |
|---|---|
@FunctionalInterface + 1 abstract method | ✅ Yes |
| No annotation + 1 abstract method | ✅ Yes |
@FunctionalInterface + 2 abstract methods | ❌ Compile error |
| No annotation + 2 abstract methods | ❌ No (not functional, but compiles) |
@FunctionalInterface when you intend an interface to be used as a functional interface. It prevents accidental addition of a second abstract method in the future and clearly communicates your design intent.1.3 What is Allowed Inside a Functional Interface?
A functional interface must have exactly one abstract method, but it can contain:
| Member Type | Allowed? | Notes |
|---|---|---|
| Abstract methods | ✅ Exactly ONE | The defining constraint |
default methods | ✅ Any number | Must have implementation body |
static methods | ✅ Any number | Must have implementation body |
| Object class methods | ✅ (do not count) | toString, equals, hashCode, etc. |
Constants (static final) | ✅ Any number | Standard interface constants |
Full Example with All Allowed Members
1@FunctionalInterface2public interface Bird {3
4 // ✅ THE one required abstract method5 void canFly(String weather);6
7 // ✅ Default method — allowed (has body)8 default void breathe() {9 System.out.println("Bird is breathing");10 }11
12 // ✅ Static method — allowed (has body)13 static String getKingdom() {14 return "Animalia";15 }16
17 // ✅ Object class method — NOT counted as abstract18 @Override19 String toString();20
21 // ❌ Would break functional interface22 // int getHeight(); // second abstract → compile error with @FunctionalInterface23}1.4 Object Class Methods in Interfaces
Background
Every Java class ultimately extends java.lang.Object. Object defines methods like:
toString()— returns a String representationequals(Object o)— checks equalityhashCode()— returns hash code
Key Rule
If an interface declares a method that matches apublicmethod signature fromjava.lang.Object, that method does NOT count as an abstract method for the purposes of functional interface rules.
This is because any class implementing the interface will already have these methods from Object — the implementing class never needs to provide them explicitly.
1@FunctionalInterface2public interface TestInterface {3 void process(); // ← the ONE abstract method (counts)4 String toString(); // ← Object class method (does NOT count)5 boolean equals(Object o); // ← Object class method (does NOT count)6}7// Still a valid functional interface — only 'process()' counts1// A class implementing this doesn't need to implement toString() or equals()2public class MyClass implements TestInterface {3 @Override4 public void process() {5 System.out.println("Processing...");6 }7 // No need to implement toString() or equals() — inherited from Object8}2. Three Ways to Implement an Interface
Before lambda expressions existed (before Java 8), there were two ways to implement an interface. Lambda expressions provide a third, more concise way.
2.1 Way 1: Using `implements` Keyword
The Traditional Approach
1// The functional interface2@FunctionalInterface3public interface Bird {4 void canFly(String weather);5}1// A concrete class that implements the interface2public class Eagle implements Bird {3 @Override4 public void canFly(String weather) {5 System.out.println("Eagle is flying in " + weather + " weather");6 }7}1// Using it2public class Main {3 public static void main(String[] args) {4 Bird eagle = new Eagle(); // Bird reference holds Eagle object5 eagle.canFly("sunny"); // Output: Eagle is flying in sunny weather6 }7}Characteristics:
- Requires creating a separate named class (
Eagle) - More verbose but most explicit
- Class can be reused across the codebase
- Best when the implementation is complex or reused in many places
2.2 Way 2: Using Anonymous Class
When You Don't Need a Reusable Named Class
1public class Main {2 public static void main(String[] args) {3
4 // Anonymous class — no separate .java file needed5 Bird eagle = new Bird() {6 @Override7 public void canFly(String weather) {8 System.out.println("Eagle is flying in " + weather + " weather");9 }10 }; // ← semicolon ends the variable declaration11
12 eagle.canFly("cloudy"); // Output: Eagle is flying in cloudy weather13 }14}What Happens Internally
The compiler creates a hidden class behind the scenes — something like:
1// What the compiler generates internally (simplified):2class Main$1 implements Bird {3 @Override4 public void canFly(String weather) {5 System.out.println("Eagle is flying in " + weather + " weather");6 }7}The class name (Main$1) is assigned by the compiler. You never see or use this name — hence "anonymous."
Characteristics:
- No separate named class required
- Verbose — lots of boilerplate (
new Bird() { @Override public void... }) - Good for one-time-use implementations
- The only option before Java 8 for quick interface implementations
2.3 Way 3: Using Lambda Expression
The Java 8 Way
1public class Main {2 public static void main(String[] args) {3
4 // Lambda expression — most concise5 Bird eagle = (weather) -> System.out.println("Eagle flying in " + weather);6
7 eagle.canFly("windy"); // Output: Eagle flying in windy weather8 }9}Why Lambdas Were Introduced
Look at the anonymous class version again:
1Bird eagle = new Bird() { // ← boilerplate2 @Override // ← boilerplate3 public void canFly(String weather) { // ← method name (redundant — only one abstract method!)4 System.out.println("Eagle is flying in " + weather + " weather"); // ← actual logic5 } // ← boilerplate6}; // ← boilerplateOnly the highlighted line is the actual logic you care about. Everything else is boilerplate (ceremony code that Java requires but adds no information).
Lambda expressions eliminate this boilerplate:
1Bird eagle = (weather) -> System.out.println("Eagle is flying in " + weather + " weather");2// ↑ param ↑ arrow ↑ the actual logic (same line as before)The key insight: since a functional interface has only one abstract method, the compiler already knows which method you're implementing. There's no need to write the method name,@Override,public void, etc.
2.4 Comparison of All Three Ways
1@FunctionalInterface2interface Bird {3 void canFly(String weather);4}| Approach | Code | Verbosity | When to Use |
|---|---|---|---|
| implements | Separate class file | High | Complex, reusable implementations |
| Anonymous class | Inline, but verbose | Medium | One-time use, before Java 8 |
| Lambda | Single line | Low | One-time use, Java 8+, preferred |
1// WAY 1: implements2public class Eagle implements Bird {3 public void canFly(String weather) {4 System.out.println("Flying in " + weather);5 }6}7Bird b1 = new Eagle();8
9// WAY 2: anonymous class10Bird b2 = new Bird() {11 @Override12 public void canFly(String weather) {13 System.out.println("Flying in " + weather);14 }15};16
17// WAY 3: lambda18Bird b3 = (weather) -> System.out.println("Flying in " + weather);19
20// All three produce identical behavior:21b1.canFly("sunny"); // Flying in sunny22b2.canFly("sunny"); // Flying in sunny23b3.canFly("sunny"); // Flying in sunny3. Lambda Expression Deep Dive
3.1 Syntax Breakdown
1(parameters) -> { body }2 ↑ ↑3 │ └── Implementation / method body4 └── Input parameters of the abstract method5 (empty if method takes no parameters)The -> is called the lambda operator or arrow operator.
Full Anatomy
1Bird eagle = (String weather) -> {2// ↑ parameter list ↑ arrow operator3 System.out.println("Flying in " + weather);4// ↑ method body5};3.2 Lambda Syntax Rules
Rule 1: Parameter Types Are Optional
The compiler can infer parameter types from the functional interface definition:
1// With explicit type (verbose but valid)2Bird b = (String weather) -> System.out.println(weather);3
4// Without type (compiler infers from interface) ← preferred5Bird b = (weather) -> System.out.println(weather);Rule 2: Single Parameter Parentheses Are Optional
1// With parentheses (always valid)2Bird b = (weather) -> System.out.println(weather);3
4// Without parentheses (only valid for exactly one parameter)5Bird b = weather -> System.out.println(weather);Rule 3: No Parameters Use Empty Parentheses
1@FunctionalInterface2interface Greeting {3 void sayHello(); // no parameters4}5
6Greeting g = () -> System.out.println("Hello!");7// ↑ empty parentheses — requiredRule 4: Single-Line Body Curly Braces and `return` Are Optional
1// Multi-line: curly braces REQUIRED2Bird b = (weather) -> {3 String msg = "Flying in " + weather;4 System.out.println(msg);5};6
7// Single-line: curly braces OPTIONAL8Bird b = (weather) -> System.out.println("Flying in " + weather);Rule 5: Single-Line with Return No `return` Keyword
When the body is a single expression that returns a value, return is implicit:
1@FunctionalInterface2interface Doubler {3 int doubleIt(int n);4}5
6// With block — needs explicit return7Doubler d = (n) -> { return n * 2; };8
9// Without block — return is implicit10Doubler d = (n) -> n * 2;3.3 Lambda Examples by Method Signature
No Parameters, No Return (`void`)
1@FunctionalInterface2interface Action {3 void execute();4}5
6Action a = () -> System.out.println("Executed!");7a.execute(); // Output: Executed!One Parameter, No Return
1@FunctionalInterface2interface Printer {3 void print(String message);4}5
6Printer p = message -> System.out.println(">> " + message);7p.print("Hello"); // Output: >> HelloOne Parameter, With Return
1@FunctionalInterface2interface Square {3 int compute(int n);4}5
6Square sq = n -> n * n;7System.out.println(sq.compute(5)); // Output: 25Two Parameters, With Return
1@FunctionalInterface2interface Adder {3 int add(int a, int b);4}5
6Adder adder = (a, b) -> a + b;7System.out.println(adder.add(3, 7)); // Output: 10Multi-Line Body
1@FunctionalInterface2interface Validator {3 boolean validate(int value);4}5
6Validator v = (value) -> {7 if (value < 0) return false;8 if (value > 100) return false;9 return true;10};11
12System.out.println(v.validate(50)); // Output: true13System.out.println(v.validate(-5)); // Output: false14System.out.println(v.validate(150)); // Output: false4. Built-in Functional Interfaces (`java.util.function`)
Java 8 introduced a package — java.util.function — that contains pre-built functional interfaces covering the most common use cases. You do not need to write your own for standard scenarios.
The four core built-in functional interfaces are:
4.1 `Consumer<T>`
Definition
`Consumer<T>`
represents an operation that accepts one input of type T and returns no result (void). It "consumes" the input.
Interface Structure
1@FunctionalInterface2public interface Consumer<T> {3 void accept(T t); // the one abstract method4}Use Cases
- Printing or logging a value
- Saving data to a database
- Sending a notification
- Performing a side effect with an input
Example
1import java.util.function.Consumer;2
3public class Main {4 public static void main(String[] args) {5
6 // Consumer that takes an Integer and logs it7 Consumer<Integer> logger = (value) -> {8 if (value > 10) {9 System.out.println("Large value: " + value);10 } else {11 System.out.println("Small value: " + value);12 }13 };14
15 logger.accept(11); // Output: Large value: 1116 logger.accept(5); // Output: Small value: 517 logger.accept(100); // Output: Large value: 10018 }19}Equivalence to Anonymous Class
1// These are IDENTICAL in behavior:2
3// Anonymous class4Consumer<Integer> logger1 = new Consumer<Integer>() {5 @Override6 public void accept(Integer value) {7 System.out.println("Value: " + value);8 }9};10
11// Lambda12Consumer<Integer> logger2 = (value) -> System.out.println("Value: " + value);4.2 `Supplier<T>`
Definition
`Supplier<T>`
represents a function that accepts no input and returns a result of type T. It "supplies" a value.
Interface Structure
1@FunctionalInterface2public interface Supplier<T> {3 T get(); // the one abstract method4}Use Cases
- Factory methods that create objects
- Lazy initialization (compute a value only when needed)
- Providing default values
- Generating random values or timestamps
Example
1import java.util.function.Supplier;2
3public class Main {4 public static void main(String[] args) {5
6 // Supplier that provides a greeting message7 Supplier<String> greetingSupplier = () -> "Hello, World!";8
9 String message = greetingSupplier.get();10 System.out.println(message); // Output: Hello, World!11
12 // Supplier that provides current timestamp13 Supplier<Long> timestampSupplier = () -> System.currentTimeMillis();14 System.out.println(timestampSupplier.get()); // Output: current time in ms15
16 // Supplier that creates a new object17 Supplier<java.util.ArrayList<String>> listSupplier = () -> new java.util.ArrayList<>();18 java.util.ArrayList<String> newList = listSupplier.get();19 }20}Single-Line vs. Block Form
1// Single-line form (no return keyword, no braces)2Supplier<String> s1 = () -> "Hello!";3
4// Block form (explicit return, with braces)5Supplier<String> s2 = () -> {6 return "Hello!";7};8
9// Both are equivalent10System.out.println(s1.get()); // Hello!11System.out.println(s2.get()); // Hello!4.3 `Function<T, R>`
Definition
`Function<T, R>`
represents a function that accepts one argument of type T and returns a result of type R. It transforms the input into an output.
Interface Structure
1@FunctionalInterface2public interface Function<T, R> {3 R apply(T t); // the one abstract method4}T— the input typeR— the return/result type
Use Cases
- Type conversion (e.g.,
Integer→String) - Data transformation / mapping
- Extracting a field from an object
- Applying a formula to a value
Example
1import java.util.function.Function;2
3public class Main {4 public static void main(String[] args) {5
6 // Function that converts Integer to String7 Function<Integer, String> intToString = (num) -> {8 return "Number is: " + num.toString();9 };10
11 String result = intToString.apply(42);12 System.out.println(result); // Output: Number is: 4213
14 // Function that squares a number15 Function<Integer, Integer> square = n -> n * n;16 System.out.println(square.apply(5)); // Output: 2517
18 // Function that converts String to its length19 Function<String, Integer> strLength = str -> str.length();20 System.out.println(strLength.apply("Hello")); // Output: 521 }22}Type Parameters in Practice
1// Function<T, R>2// ↑ ↑3// │ └── Return type4// └── Input type5
6Function<Integer, String> // takes int, returns String7Function<String, Boolean> // takes String, returns Boolean8Function<Double, Integer> // takes Double, returns Integer9Function<String, String> // takes String, returns String (transform)4.4 `Predicate<T>`
Definition
`Predicate<T>`
represents a function that accepts one argument of type T and always returns a boolean. It tests whether the input satisfies a condition.
Interface Structure
1@FunctionalInterface2public interface Predicate<T> {3 boolean test(T t); // the one abstract method4}Use Cases
- Validation logic (is this input valid?)
- Filtering collections
- Conditional checks
- Testing properties (is even, is empty, is above threshold)
Example
1import java.util.function.Predicate;2
3public class Main {4 public static void main(String[] args) {5
6 // Predicate that checks if a number is even7 Predicate<Integer> isEven = (value) -> {8 if (value % 2 == 0) return true;9 else return false;10 };11
12 // Simplified single-line version13 Predicate<Integer> isEvenSimple = value -> value % 2 == 0;14
15 System.out.println(isEven.test(4)); // Output: true16 System.out.println(isEven.test(7)); // Output: false17
18 // Predicate for String validation19 Predicate<String> isNotEmpty = str -> !str.isEmpty();20 System.out.println(isNotEmpty.test("hello")); // Output: true21 System.out.println(isNotEmpty.test("")); // Output: false22
23 // Predicate for age validation24 Predicate<Integer> isAdult = age -> age >= 18;25 System.out.println(isAdult.test(20)); // Output: true26 System.out.println(isAdult.test(15)); // Output: false27 }28}The Abstract Method is `test()` Why We Don't Write It in Lambda
1// With anonymous class — must name the method2Predicate<Integer> p = new Predicate<Integer>() {3 @Override4 public boolean test(Integer value) { // ← must write 'test'5 return value % 2 == 0;6 }7};8
9// With lambda — no method name needed10Predicate<Integer> p = value -> value % 2 == 0;11// Java knows this implements test() because:12// 1. Predicate is a functional interface13// 2. It has only one abstract method (test)14// 3. The lambda must be implementing that one method4.5 Built-in Types Comparison Table
| Interface | Abstract Method | Input | Output | Use When |
|---|---|---|---|---|
Consumer | void accept(T t) | T | Nothing | Process/consume input with side effects |
Supplier | T get() | Nothing | T | Generate/supply a value |
Function | R apply(T t) | T | R | Transform input to output |
Predicate | boolean test(T t) | T | boolean | Test/validate a condition |
Memory Device
1Consumer — takes IN, gives nothing out ("consumes")2Supplier — takes nothing in, gives OUT ("supplies")3Function — takes IN, gives OUT ("transforms")4Predicate — takes IN, gives TRUE/FALSE ("tests")Additional Built-in Variants (Bonus)
Java provides many variations of these four core interfaces:
| Interface | Description |
|---|---|
BiConsumer | Like Consumer but accepts two inputs |
BiFunction | Like Function but accepts two inputs |
BiPredicate | Like Predicate but accepts two inputs |
UnaryOperator | Function — input and output same type |
BinaryOperator | Like BiFunction — both inputs and output same type |
IntConsumer, LongConsumer | Primitive-specialized versions (avoid boxing) |
5. Functional Interface Inheritance Use Cases
Interfaces can extend other interfaces. When functional interfaces are involved, specific rules apply. There are three important use cases.
5.1 Use Case 1: Functional Extending Non-Functional
Scenario: A `@FunctionalInterface` tries to extend an interface that has an abstract method
1// Non-functional interface — has one abstract method2public interface LivingThing {3 void canBreathe(); // abstract method #14}5
6// Functional interface tries to extend LivingThing7@FunctionalInterface8public interface Bird extends LivingThing {9 void canFly(String weather); // abstract method #2 (inherited + own = 2 total)10}11// ❌ COMPILE ERROR: Multiple non-overriding abstract methods found in interface BirdWhy? When Bird extends LivingThing, it inherits canBreathe(). Now Bird has two abstract methods: canBreathe() (inherited) + canFly() (own). Two abstract methods → cannot be a functional interface.
Fix: Make the Parent Method `default`
1// Non-functional interface — method is default (has body)2public interface LivingThing {3 default void canBreathe() {4 System.out.println("Breathing...");5 }6}7
8// Functional interface extends it — only one abstract method (canFly)9@FunctionalInterface10public interface Bird extends LivingThing {11 void canFly(String weather); // only ONE abstract method ✅12}canBreathe() is now a default method — it has an implementation and is not abstract. Bird inherits it but is not required to implement it. Bird has exactly one abstract method → valid functional interface.
5.2 Use Case 2: Non-Functional Extending Functional
Scenario: A regular interface extends a functional interface
1// Functional interface — one abstract method2@FunctionalInterface3public interface LivingThing {4 void canBreathe(); // abstract method #15}6
7// Regular interface (NOT @FunctionalInterface) extends LivingThing8public interface Bird extends LivingThing {9 void canFly(String weather); // abstract method #210}11// ✅ COMPILES FINEWhy does this work? Bird is a regular interface (no @FunctionalInterface annotation). Regular interfaces can have any number of abstract methods. Bird has two (one inherited, one own) — that is perfectly legal.
However: Bird is now NOT a functional interface (two abstract methods), so you cannot use a lambda to implement it.
1// ❌ Cannot use lambda — Bird has two abstract methods2// Bird b = () -> System.out.println("breathing"); // Which method does this implement?3
4// ✅ Must use anonymous class or implements5Bird b = new Bird() {6 @Override public void canBreathe() { System.out.println("Breathing"); }7 @Override public void canFly(String w) { System.out.println("Flying in " + w); }8};5.3 Use Case 3: Functional Extending Functional
Scenario A: Both have DIFFERENT abstract methods Compile Error
1@FunctionalInterface2public interface LivingThing {3 void canBreathe(); // abstract method #14}5
6@FunctionalInterface7public interface Bird extends LivingThing {8 void canFly(String weather); // abstract method #2 (different from canBreathe)9}10// ❌ COMPILE ERROR: Bird ends up with two different abstract methodsThe child inherits canBreathe() from LivingThing and adds canFly(). Two different abstract methods → @FunctionalInterface constraint violated.
Scenario B: Both have the SAME abstract method Valid
1@FunctionalInterface2public interface LivingThing {3 boolean canBreathe(); // abstract method4}5
6@FunctionalInterface7public interface Bird extends LivingThing {8 boolean canBreathe(); // SAME signature as parent9}10// ✅ VALID — Bird's canBreathe() overrides (re-declares) LivingThing's canBreathe()11// Only ONE effective abstract methodWhy does this work? When Bird declares a method with the exact same signature as the inherited one, it is effectively overriding (re-declaring) it. The result is still just one abstract method — it is not counted twice.
Implementing the Valid Inheritance Case
1@FunctionalInterface2public interface LivingThing {3 boolean canBreathe();4}5
6@FunctionalInterface7public interface Bird extends LivingThing {8 boolean canBreathe(); // same signature — valid9}10
11public class Main {12 public static void main(String[] args) {13
14 // Lambda implementing Bird (which extends LivingThing)15 // No parameters → empty ()16 // Returns boolean → just return true (no braces needed for single expression)17 Bird eagleLambda = () -> true;18
19 System.out.println(eagleLambda.canBreathe()); // Output: true20 }21}Inheritance Rules Summary
6. Writing Your Own Functional Interface
Use a built-in functional interface when your use case fits one of the four patterns (Consumer, Supplier, Function, Predicate).
Write your own when:
- You need more than one or two parameters
- The semantics are domain-specific and a custom name improves readability
- The built-in types don't express your intent clearly
Custom Functional Interface Examples
1// Custom: 3 parameters, returns a String2@FunctionalInterface3public interface TriFunction<A, B, C, R> {4 R apply(A a, B b, C c);5}6
7// Usage8TriFunction<String, Integer, Boolean, String> formatter =9 (name, age, active) -> name + " | Age: " + age + " | Active: " + active;10
11System.out.println(formatter.apply("Alice", 30, true));12// Output: Alice | Age: 30 | Active: true1// Custom: domain-specific name improves clarity2@FunctionalInterface3public interface TaxCalculator {4 double calculate(double grossIncome, double taxRate);5}6
7TaxCalculator basic = (income, rate) -> income * rate / 100;8System.out.println(basic.calculate(100000, 30)); // Output: 30000.01// Custom: no input, no output (Runnable-like)2@FunctionalInterface3public interface DatabaseOperation {4 void execute() throws Exception;5}6
7DatabaseOperation saveUser = () -> System.out.println("Saving user to DB...");7. Summary Diagrams
Lambda vs. Anonymous Class
Four Built-in Functional Interfaces
Functional Interface Inheritance Decision Tree
8. Common Mistakes
Mistake 1: Adding a Second Abstract Method to a `@FunctionalInterface`
1@FunctionalInterface2public interface Bird {3 void canFly(String weather);4 int getHeight(); // ❌ COMPILE ERROR5}Fix: Remove the second abstract method, or make it default with an implementation.
Mistake 2: Using Lambda with a Non-Functional Interface
1public interface Bird {2 void canFly(String weather);3 int getHeight(); // two abstract methods4}5
6// ❌ COMPILE ERROR: Bird is not a functional interface7Bird b = weather -> System.out.println(weather);Fix: Use anonymous class or implements, or reduce the interface to one abstract method.
Mistake 3: Wrong Argument Count in Lambda
1@FunctionalInterface2interface Adder {3 int add(int a, int b); // two parameters4}5
6// ❌ COMPILE ERROR: wrong number of arguments7Adder adder = (a) -> a + 1;8
9// ✅ CORRECT10Adder adder = (a, b) -> a + b;Mistake 4: Using `return` in a Single-Line Lambda Without Braces
1@FunctionalInterface2interface Square {3 int compute(int n);4}5
6// ❌ COMPILE ERROR: return not allowed in expression lambda7Square sq = n -> return n * n;8
9// ✅ CORRECT — no return, no braces for single expression10Square sq = n -> n * n;11
12// ✅ ALSO CORRECT — return with braces13Square sq2 = n -> { return n * n; };Mistake 5: Empty Parentheses Missing for Zero-Parameter Lambda
1@FunctionalInterface2interface Action {3 void execute(); // no parameters4}5
6// ❌ COMPILE ERROR: syntax error7Action a = -> System.out.println("Hello");8
9// ✅ CORRECT — empty parentheses required10Action a = () -> System.out.println("Hello");Mistake 6: Thinking `default` Methods Break the Functional Interface Rule
1@FunctionalInterface2public interface Bird {3 void canFly(String weather); // abstract — counts4 default void breathe() { } // default — does NOT count5 static void info() { } // static — does NOT count6}7// ✅ VALID — still a functional interfacedefault, static, and Object-class methods are completely ignored in this count.Mistake 7: Forgetting Semicolon After Lambda Expression Statement
1// ❌ Missing semicolon2Bird b = weather -> System.out.println(weather)3
4// ✅ Correct5Bird b = weather -> System.out.println(weather);9. Best Practices
- Always add
@FunctionalInterfacewhen designing an interface intended for lambda use — it enforces the contract and documents intent. - Prefer built-in functional interfaces (
Consumer,Supplier,Function,Predicate) over custom ones when the signature fits. - Keep lambdas short — if a lambda body is more than 2-3 lines, consider extracting it into a named method (improves readability and testability).
- Use method references when the lambda simply calls an existing method:
1 // Lambda2 Consumer<String> printer = s -> System.out.println(s);3 // Method reference (more readable)4 Consumer<String> printer = System.out::println;- Don't mutate external state inside lambdas — lambdas should ideally be pure functions (same input → same output, no side effects) for predictability and thread safety.
- Use
Predicatefor validation chains —Predicatehas built-inand(),or(),negate()for composing conditions:
1 Predicate<Integer> isPositive = n -> n > 0;2 Predicate<Integer> isEven = n -> n % 2 == 0;3 Predicate<Integer> isPositiveAndEven = isPositive.and(isEven);- Name lambda variables descriptively —
isEven,userValidator,taxCalculatorare better thanp,f,c.
10. Interview Notes
Commonly Asked Questions
Q1: What is a functional interface?
Answer: An interface with exactly one abstract method. Also called a SAM (Single Abstract Method) interface. It can have any number of default methods, static methods, and Object-class methods — only abstract methods are counted.
Q2: What is `@FunctionalInterface`? Is it mandatory?
Answer: It is an optional annotation that tells the compiler to enforce the one-abstract-method constraint. Without it, an interface with one abstract method is still a functional interface, but the annotation adds compile-time enforcement and documents intent.
Q3: What is a lambda expression? Why was it introduced?
Answer: A lambda expression is a concise way to implement a functional interface. It was introduced in Java 8 to reduce the boilerplate of anonymous classes. Since a functional interface has exactly one abstract method, the lambda's parameters and body are enough — no class name, method name, or @Override needed.
Q4: What is the syntax of a lambda expression?
Answer: (parameters) -> body
- Parameters: empty
()if none, or(param1, param2, ...). Type annotations optional. - Body: single expression (no braces, implicit return) or block
{ ... }(needs explicitreturnfor non-void).
Q5: Can a functional interface have `default` and `static` methods?
Answer: Yes. default and static methods do not count toward the one-abstract-method limit. A functional interface can have any number of them as long as it has exactly one abstract method.
Q6: What are the four core built-in functional interfaces in Java?
Answer:
Consumer— accepts T, returns nothing. Method:accept()Supplier— accepts nothing, returns T. Method:get()Function— accepts T, returns R. Method:apply()Predicate— accepts T, returns boolean. Method:test()
Q7: Can a functional interface extend another interface?
Answer: Yes, with rules:
- If the parent has an abstract method and the child adds a different abstract method → two abstract methods total → not a functional interface.
- If the parent has an abstract method and the child re-declares the same signature → still one effective abstract method → valid.
- If the parent only has
defaultmethods → child's one abstract method is fine → valid.
Q8: Why can lambdas only be used with functional interfaces?
Answer: Lambda expressions work by implementing a method without naming it. This only works when there is exactly one abstract method — otherwise the compiler cannot determine which method the lambda implements.
Q9: What is the difference between `Function<T,R>` and `Consumer<T>`?
Answer: Function accepts T and returns R (transforms input to output). Consumer accepts T and returns nothing — it performs a side effect (print, save, send).
Q10: What is the difference between a lambda and an anonymous class?
Answer: Both implement an interface inline. A lambda is more concise — it omits the class declaration, method name, and @Override. A lambda can only implement functional interfaces (one abstract method). An anonymous class can implement any interface or extend any class.
11. Practice Questions
Easy
- What is the defining characteristic of a functional interface?
- What does SAM stand for? What does it mean?
- Is
@FunctionalInterfacemandatory? What does it do? - Write a functional interface
Greeterwith one methodgreet(String name)that returnsvoid. - Can a functional interface have
defaultmethods? Static methods? Object-class methods? - Which abstract method does
Consumerexpose? What does it accept and return?
Medium
- Implement the
Greeterinterface from Q4 using all three approaches:implements, anonymous class, and lambda expression. - Write a
Consumerlambda that prints the string in uppercase. - Write a
Supplierlambda that returns a random integer between 1 and 100. - Write a
Functionlambda that returns the number of vowels in a string. - Write a
Predicatelambda that returnstrueif the string starts with an uppercase letter. - Explain why the following code has a compile error, and fix it:
1 @FunctionalInterface2 interface MyInterface {3 void doSomething();4 void doSomethingElse();5 }- Given this interface, can you use a lambda? Why or why not?
1 public interface Vehicle {2 void start();3 void stop();4 }Hard
- Write a functional interface
TriFunctionthat accepts three inputs and returns a result. Implement it with a lambda that concatenates three strings with a separator. - Create two functional interfaces where one extends the other with the same method signature. Implement it with a lambda. Then show what happens if you change the child interface to use a different method signature.
- Explain the three rules of lambda syntax (parameter types, parentheses, braces/return). Write four lambda examples progressively simplifying the syntax for: a two-parameter int adder.
- Implement a mini-pipeline using all four built-in interfaces in sequence:
- A
Supplierprovides raw data - A
Functiontransforms it - A
Predicatevalidates it - A
Consumerconsumes (prints) the result
- Explain why
Predicateis preferable toFunctionwhen testing conditions, even though both return a boolean value. (Hint: think about the built-inand(),or(),negate()methods.)
12. Quick Revision Summary
1☕ FUNCTIONAL INTERFACES & LAMBDA EXPRESSIONS — KEY POINTS2
3📌 FUNCTIONAL INTERFACE:4 = Interface with EXACTLY ONE abstract method5 = SAM (Single Abstract Method) interface6 @FunctionalInterface → optional annotation, enforces the rule at compile time7
8 ALLOWED inside functional interface:9 ✅ Exactly 1 abstract method (required)10 ✅ Any number of default methods (don't count)11 ✅ Any number of static methods (don't count)12 ✅ Object class methods (don't count)13
14🔧 THREE WAYS TO IMPLEMENT:15 1. implements keyword → separate named class16 2. Anonymous class → inline, verbose17 3. Lambda expression → inline, concise (Java 8+)18
19 Lambda can ONLY implement FUNCTIONAL interfaces (1 abstract method)20
21📝 LAMBDA SYNTAX:22 (parameters) -> body23
24 Rules:25 • No params → ()26 • One param → (x) or just x27 • Multi params → (x, y)28 • Types optional → compiler infers29 • Single-line body → no braces, no return30 • Multi-line body → { } required, return required31
32 Examples:33 () -> "Hello" // no params, returns String34 x -> x * 2 // one param, returns int35 (x, y) -> x + y // two params, returns int36 (x) -> { System.out.println(x); } // one param, void, multi-line37
38📦 4 BUILT-IN FUNCTIONAL INTERFACES (java.util.function):39 Consumer<T> → accept(T) Input: T | Output: void40 Supplier<T> → get() Input: none | Output: T41 Function<T,R> → apply(T) Input: T | Output: R42 Predicate<T> → test(T) Input: T | Output: boolean43
44 Consumer = consumes, no return45 Supplier = supplies, no input46 Function = transforms T to R47 Predicate = tests, returns true/false48
49🔗 FUNCTIONAL INTERFACE INHERITANCE:50 Functional extends Non-Functional:51 → If parent has abstract method → 2 total → ❌ ERROR52 → If parent has only default → 1 total → ✅ OK53
54 Non-Functional extends Functional:55 → Adds its own abstract method → 2 total → ✅ Compiles (not functional)56
57 Functional extends Functional:58 → Same method signature → 1 effective → ✅ OK59 → Different signatures → 2 total → ❌ ERROR60
61⚠️ KEY INTERVIEW POINTS:62 • Lambda works ONLY with functional interfaces (1 abstract method)63 • @FunctionalInterface is OPTIONAL but recommended64 • default/static methods do NOT count toward the limit65 • Consumer = no return | Supplier = no input | Function = both | Predicate = boolean return66 • Lambda = less verbose anonymous class for functional interfaces67 • Cannot use return without braces; cannot use braces without return (for non-void)End of Chapter — Functional Interfaces & Lambda Expressions
ClassName::methodName) — an even more concise form of lambdas
- Stream API — uses functional interfaces extensively (filter, map, forEach)
- Optional — uses Supplier, Consumer, Predicate in its API
- volatile keyword in depth — for the memory visibility concepts introduced in the Singleton lectureStudy Guide generated from: Java Basics to Advanced — Interfaces Part (Final): Functional Interfaces & Lambda Expressions
Practice & Implement
Apply what you learned in Functional Interfaces & Lambdas
Given a list of integers 1-10, filter odd numbers, square them, sort, and print each.
1 9 25 49 81
Mastery check
How well can you recall this?
Finished this lesson?