A Functional Interface (also known as a SAM — Single Abstract Method interface) is an interface that contains strictly one abstract method. Functional interfaces provide the target type definitions for all lambda expressions and method references in Java.
java.util.function| Interface | Method Signature | Input → Output | Primary Real-World Use Case |
|---|---|---|---|
Predicate<T> |
boolean test(T t) |
One Object → boolean |
Filtering data and evaluating conditional rules |
Function<T, R> |
R apply(T t) |
One Object (T) → One Object (R) | Transforming or mapping data types |
Consumer<T> |
void accept(T t) |
One Object (T) → void |
Consuming data (printing, logging, saving) |
Supplier<T> |
T get() |
No Arguments → One Object (T) | Factory methods, generating timestamps/IDs |
import java.util.function.Predicate;
import java.util.function.Function;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.time.LocalDateTime;
public class FunctionalInterfacesDemo {
public static void main(String[] args) {
// 1. Predicate: Check if number is positive
Predicate<Integer> isPositive = n -> n > 0;
System.out.println("Is 15 positive? " + isPositive.test(15)); // true
// 2. Function: Convert String to its Character Length
Function<String, Integer> lengthMapper = s -> s.length();
System.out.println("Length of 'Veewom': " + lengthMapper.apply("Veewom")); // 6
// 3. Consumer: Print greeting to console
Consumer<String> greeter = name -> System.out.println("Hello, " + name + "!");
greeter.accept("Aarav"); // Hello, Aarav!
// 4. Supplier: Produce current timestamp
Supplier<LocalDateTime> clock = () -> LocalDateTime.now();
System.out.println("Current Time: " + clock.get());
}
}
Now let us explore the revolutionary Java Stream API: Declarative, pipeline-based data processing. Proceed to: Java Stream API & Pipelines →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Implementing functional interfaces.
Passing predicates and functions to streams.
Using Supplier and Consumer.
Default and static methods.