🧠 What is a Functional Interface?
A functional interface in Java is an interface with exactly one abstract method. These are the backbone of lambda expressions and method references, introduced in Java 8 to bring functional programming features to the language.
Every functional interface can have multiple default or static methods, but only one abstract method.
✅ Common Functional Interfaces from JDK
Here are some of the most commonly used functional interfaces directly from the Java Standard Library:
1. Runnable (java.lang.Runnable
)
java
Runnable r = () -> System.out.println("Running a thread!");
new Thread(r).start();
- Represents a task that can be executed concurrently.
- Has the method:
void run()
2. Callable (java.util.concurrent.Callable
)
java
Callable<String> c = () -> "Callable result";
- Similar to
Runnable
, but returns a result and may throw an exception. - Has the method:
V call() throws Exception
3. Comparator<T> (java.util.Comparator
)
java
Comparator<String> comparator = (s1, s2) -> s1.length() - s2.length();
- Used to compare two objects.
- Has the method:
int compare(T o1, T o2)
4. Consumer<T> (java.util.function.Consumer
)
java
Consumer<String> printer = s -> System.out.println(s);
printer.accept("Hello, Consumer!");
- Takes a single input and returns nothing.
- Has the method:
void accept(T t)
5. Supplier<T> (java.util.function.Supplier
)
java
Supplier<Double> randomSupplier = () -> Math.random();
System.out.println(randomSupplier.get());
- Provides a result without taking any input.
- Has the method:
T get()
6. Predicate<T> (java.util.function.Predicate
)
java
Predicate<String> isEmpty = s -> s.isEmpty();
System.out.println(isEmpty.test("")); // true
- Accepts one input and returns a boolean.
- Has the method:
boolean test(T t)
7. Function<T, R> (java.util.function.Function
)
java
Function<String, Integer> lengthMapper = s -> s.length();
System.out.println(lengthMapper.apply("Function")); // 8
- Accepts one input and produces a result.
- Has the method:
R apply(T t)
8. BiFunction<T, U, R> (java.util.function.BiFunction
)
java
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println(add.apply(5, 3)); // 8
- Takes two inputs and returns a result.
- Has the method:
R apply(T t, U u)
📦 Where Are These Used?
These interfaces are widely used in:
- Streams API
- Concurrency utilities
- Lambda expressions
- Collections operations
- Asynchronous and reactive programming
🔚 Conclusion
Java 8's java.util.function
package brought a robust set of predefined functional interfaces to streamline functional programming. Mastering these interfaces is essential for writing clean, concise, and modern Java code.