Predicate Functional Interface Java 8

Predicate Predefined Functional Interface in Java 8

Articles & Tutorials Programming

What is Predicate:

A predicate is a function with a single argument and returns a boolean value.
To implement predicate functions in Java, Oracle people introduced the Predicate interface in 1.8 version (i.e., Predicate<T>).
Predicate interface present in Java.util.function package.
It’s a functional interface and it contains only one method i.e., test()

 

Predicate Prototype:

interface Predicate<T> {
    public boolean test(T t);
}

As predicate is a functional interface and hence it can refer to the lambda expression

Example: Write a predicate to check whether the given integer is greater than 7 or not.

Without Lambda expression:

public boolean test(Integer I) {

     if (I >7) {
         return true;
     } else {
         return false;
     }

}

With Lambda expression:

(Integer I) -> {

     if(I > 7) return true;
     else return false;
}

Simplified:

I -> (I>7);

The Predicate will be :

predicate<Integer> p = I -> (I >7);

To call the Predicate:

System.out.println (p.test(10));  //true
System.out.println (p.test(5)); //false

 

Predicate joining:

It’s possible to join predicates into a single predicate by using the following methods.

  • and()
  • or()
  • negate()

These are exactly same as logical AND, OR complement operators

 

Example:

Write a predicate to check whether the given integer is greater than 7 or not and the number is even or not.

Here, we create two Predicate and we use joining method to get the final Predicate

1. Number is greater than 7 or not:

Predicate<Integer> p1 = x -> x>7;

2. Number is even or not:

Predicate<Integer> p2 = y -> y % 2 == 0;

3. Final Predicate:

Predicate<Integer> p3 = p1.and(p2);

 

Related Post: Lambda Expressions with Collections in Java 8

 

Leave a Reply

Your email address will not be published. Required fields are marked *