Previous examples used manually defined functional interfaces to illustrate the basic concepts.
However, JDK 8 introduced the java.util.function package, which provides predefined functional interfaces for ease of use.
java.util.function package
Offers several ready-to-use functional interfaces.
Reduces the need to create custom interfaces.
Benefits
Simplifies development.
Standardizes the use of functional interfaces in projects.
Facilitates integration with modern Java APIs.
Using the Predicate Interface
Defines an abstract method called test(T val).
Returns true if the value meets a specific condition or restriction.
Example of Usage
Implements a lambda expression to check if a number is even.
The lambda expression is assigned to an object of type Predicate.
Working of the test Method
Evaluates the value provided as an argument.
Returns true if the number is even, otherwise returns false.
Benefit
// Uses the internal Predicate functional interface.
// Import the Predicate interface.
import java.util.function.Predicate;
class UsePredicateInterface {
public static void main(String args[])
{
// This lambda expression uses Predicate
// determine if a number is even.
Predicate
if(isEven.test(4)) System.out.println("4 is even");
if(!isEven.test(5)) System.out.println("5 is odd");
}
}
The above is the detailed content of Predefined functional interfaces. For more information, please follow other related articles on the PHP Chinese website!