Functional Interfaces in Java
Functional Interfaces in Java
📝 Table of Contents
1. What Are Functional Interfaces?🤔
2. Why Should You Care About Functional Interfaces? 💡
3. The Anatomy of a Functional Interface 🧬
4. Common Built-In Functional Interfaces 🔧
Predicate✅
Consumer 🛠️
Supplier🎁
Function🔄
5. How Do Lambda Expressions Fit In? 🧑💻
6. Creating Your Own Functional Interfaces 🎨
7. Real-World Examples 🌍
8. Working with Functional Interfaces in Collections 📦
9. Functional Interfaces and Streams API 🌊
10. From Anonymous Classes to Lambdas ✨
11. How Functional Interfaces Help with Multithreading ⚡
12. Handling Exceptions in Functional Interfaces 🚨
🏆
13. Fun Challenges and Exercises
🎁
14. Wrapping It All Up
15. Resources for More Learning📚
1. What Are Functional Interfaces? 🤔
A functional interface is a special kind of interface in Java that has only one abstract
method. This is what allows Java to embrace functional programming, which is awesome for
making code more modular and concise. 🎯
@FunctionalInterface
public interface Action {
void perform();
}
The @FunctionalInterface annotation isn’t mandatory, but it’s a helpful reminder to ensure
the interface meets the criteria of having just one abstract method.
@FunctionalInterface
interface Greeting {
void sayHello(String name);
}
So simple! 😍
a) Predicate ✅
A Predicate is like a bouncer at the club, letting in only those who meet the condition. 🎉
@FunctionalInterface
interface Predicate<T> {
boolean test(T t);
}
Example:
b) Consumer 🛠️
A Consumer consumes something and does something with it but doesn’t return anything. 🍽️
@FunctionalInterface
interface Consumer<T> {
void accept(T t);
}
Example:
c) Supplier 🎁
A Supplier provides something without any input, like a gift box 🎁 that gives you something
when you open it!
@FunctionalInterface
interface Supplier<T> {
T get();
}
Example:
d) Function 🔄
A Function takes an input and transforms it into another result. 💡
@FunctionalInterface
interface Function<T, R> {
R apply(T t);
}
Example:
@FunctionalInterface
interface StringManipulator {
String manipulate(String input);
}
7. Real-World Examples 🌍
Functional interfaces can be incredibly useful in real-world applications. Let’s take a look at a
few examples. 📈
Scenario 1: Filtering a List of People by Age
Let’s say you have a list of people, and you want to filter out the ones who are under 18. You
can easily do this with a Predicate.
class Person {
String name;
int age;
@Override
public String toString() {
return name + ": " + age;
}
}
people.stream()
.filter(isAdult::test)
.forEach(System.out::println);
}
}
Functional interfaces are often used in GUI applications for event listeners.
@FunctionalInterface
interface ButtonClickListener {
void onClick();
}
names.stream()
.filter(name -> name.length() > 4)
.map(String::toUpperCase)
.forEach(System.out::println); // JOHN, SARAH