Home > Java > javaTutorial > Predefined functional interfaces

Predefined functional interfaces

Linda Hamilton
Release: 2025-01-14 08:18:42
Original
938 people have browsed it
  • 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.

Interfaces funcionais predefinidas

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

  • Allows you to use dynamic conditions in a simple and reusable way in lambda expressions.

// 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 for
// determine if a number is even.
Predicate isEven = (n) -> (n %2) == 0;
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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template