Functional Interface
Definition and Purpose:
Functional Interface in Java is an interface that contains only one abstract method. Functional interfaces are used to provide target types for lambda expressions and method references. They enable functional programming features in Java, allowing developers to write more concise and expressive code.
The primary purpose of functional interfaces is to enable the use of lambda expressions and method references. Lambda expressions can be used to provide implementations for the single abstract method of functional interfaces, making code more readable and maintainable.
java.util.function Package:
The java.util.function
package in Java provides a collection of functional interfaces that represent different types of operations that can be performed on data. These interfaces are designed to be used with lambda expressions and method references.
Built-in Functional Interfaces:
Predicate<T>:
Represents a predicate (boolean-valued function) of one argument.
Example:
Consumer<T>:
Represents an operation that takes a single input argument and returns no result.
Example:
Function<T, R>:
Represents a function that takes one argument and produces a result.
Example:
Supplier<T>:
Represents a supplier of results.
Example:
UnaryOperator<T>:
Represents an operation on a single operand that produces a result of the same type as its operand.
Example:
BinaryOperator<T>:
Represents an operation upon two operands of the same type, producing a result of the same type as the operands.
Example:
These functional interfaces allow developers to pass behavior in a more flexible way, making it easier to write generic and reusable code in Java. They can be used in various contexts, including collections, streams, and concurrent programming. Functional interfaces, along with lambda expressions, form the foundation of functional programming in Java.
Last updated