What are functional interfaces, and how are they used?
A functional interface is an interface in Java that has exactly one abstract method. They are primarily used as the target types for lambda expressions and method references in Java.
Key Features of Functional Interfaces
- Single Abstract Method (SAM):
- A functional interface must contain only one abstract method. It can have multiple default or static methods, but only one abstract method.
@FunctionalInterface interface MyFunctionalInterface { void performAction(); // One abstract method default void defaultMethod() { System.out.println("Default method"); } }
@FunctionalInterface
Annotation:- This annotation is optional but recommended. It helps ensure the interface meets the requirements of a functional interface by causing a compile-time error if the interface has more than one abstract method.
- Lambda Expressions:
- Functional interfaces enable the use of lambda expressions, providing a clear and concise way to represent single-method interfaces.
MyFunctionalInterface action = () -> System.out.println("Action performed"); action.performAction(); // Output: Action performed
Common Functional Interfaces in Java
-
Runnable
: Represents a task that can be executed in a separate thread.Runnable r = () -> System.out.println("Running...");
-
Predicate<T>
: Represents a condition (a boolean-valued function) on an object of typeT
.Predicate<String> isEmpty = str -> str.isEmpty();
-
Function<T, R>
: Takes an argument of typeT
and returns a result of typeR
.Function<Integer, String> intToString = i -> String.valueOf(i);
-
Consumer<T>
: Represents an operation that takes an argument of typeT
and returns no result (consumes the input).Consumer<String> printString = str -> System.out.println(str);
How Are They Used?
-
Lambda Expressions: Functional interfaces are typically used with lambda expressions to pass behavior as parameters or return them from methods.
List<String> words = Arrays.asList("Java", "Python", "C++"); words.forEach(word -> System.out.println(word)); // Consumer interface used here
-
Method References: They can also be used with method references to simplify code.
words.forEach(System.out::println); // Using method reference with Consumer
Benefits
- Concise Code: They make it easy to write and pass behavior as arguments without needing boilerplate code.
- Functional Programming: They enable functional programming features like lambda expressions and method references in Java.
In summary, functional interfaces are interfaces with a single abstract method, widely used in Java to represent behavior that can be passed around as parameters, especially when working with lambda expressions and method references.