Functional Interface in Java – Complete Guide with Examples
Learn what a Functional Interface is in Java, why it is important, how to create one, and how it works with Lambda Expressions and Method References.
Functional Interface
in Java
Write less code.
Do more with Lambda.
What You'll Learn
1. Introduction
A Functional Interface in Java is an interface that contains exactly one abstract method. Functional interfaces are an important part of Java 8's functional programming features.
They are commonly used with Lambda Expressions, Method References and the Stream API.
2. What is a Functional Interface in Java?
A functional interface contains exactly one abstract method. However, it can contain multiple default and static methods.
@FunctionalInterface
interface MyFunction {
void execute();
}
3. Why Use Functional Interfaces?
Functional interfaces allow developers to represent behavior as a value and pass that behavior to methods.
Key Benefits
- Enables Lambda Expressions
- Reduces boilerplate code
- Improves readability
- Supports functional programming
- Works with Stream API
- Supports Method References
4. Examples of Functional Interfaces
Java provides several commonly used functional interfaces through the java.util.function package.
- Predicate
- Function
- Consumer
- Supplier
- UnaryOperator
- BinaryOperator
5. Functional Interface with Lambda Expression
Lambda expressions provide a concise way to implement a functional interface.
Example
@FunctionalInterface
interface Calculator {
int add(int a, int b);
}
public class Main {
public static void main(String[] args) {
Calculator calculator =
(a, b) -> a + b;
int result =
calculator.add(10, 20);
System.out.println(result);
}
}
6. Practical Example
Functional interfaces are commonly used while processing collections.
List<Integer> numbers =
Arrays.asList(10, 15, 20, 25, 30);
List<Integer> evenNumbers =
numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);
7. Output
8. Common Mistakes
Common Mistakes to Avoid
- Adding more than one abstract method
- Forgetting @FunctionalInterface
- Confusing default and abstract methods
- Recreating standard Java functional interfaces
9. Best Practices
Recommended Practices
- Use @FunctionalInterface
- Prefer standard interfaces when appropriate
- Keep interfaces focused
- Use meaningful method names
10. Functional Interface Interview Questions
11. Functional Interface PDF Notes
Functional Interface in Java
Download the PDF version of this article for offline reading and interview revision.
12. Frequently Asked Questions
13. Conclusion
Functional Interfaces are an important feature introduced in Java 8.
They provide the foundation for Lambda Expressions, Method References and several functional programming features in modern Java.
Understanding Functional Interfaces is useful for both real-world Java development and Java developer interview preparation.