Java - Predicate<T> Interface


A predicate represents a condition that is either true or false for a given input.

Predicate interface contains the following default and static methods to compose a predicate based on other predicates using logical NOT, AND, and OR.

default Predicate<T> negate()
default Predicate<T> and(Predicate<? super T> other)
default Predicate<T> or(Predicate<? super T> other)
static <T> Predicate<T> isEqual(Object targetRef)

negate() method returns a Predicate that negates the original predicate.

and() method returns a short-circuiting logical AND predicate of this predicate and other predicate.

or() method returns a short-circuiting logical OR predicate of this predicate and other predicate.

isEqual() method returns a predicate that tests if the specified targetRef is equal to the specified argument according to Objects.equals(Object o1, Object o2); if two inputs are null, this predicate evaluates to true.

The following code shows some examples of creating and using predicates:


import java.util.function.Predicate;

public class Main {
  public static void main(String[] args) {
    // Create some predicates
    Predicate<Integer> greaterThanTen = x -> x > 10;
    Predicate<Integer> divisibleByThree = x -> x % 3 == 0;
    Predicate<Integer> divisibleByFive = x -> x % 5 == 0;
    Predicate<Integer> equalToTen = Predicate.isEqual(null);

    // Create predicates using NOT, AND, and OR on other predicates
    Predicate<Integer> lessThanOrEqualToTen = greaterThanTen.negate();
    Predicate<Integer> divisibleByThreeAndFive = divisibleByThree.and(divisibleByFive);
    Predicate<Integer> divisibleByThreeOrFive = divisibleByThree.or(divisibleByFive);

    // Test the predicates
    int num = 15;
    System.out.println("Number: " + num);
    System.out.println("greaterThanTen: " + greaterThanTen.test(num));
    System.out.println("divisibleByThree: " + divisibleByThree.test(num));
    System.out.println("divisibleByFive: " + divisibleByFive.test(num));
    System.out.println("lessThanOrEqualToTen: " + lessThanOrEqualToTen.test(num));
    System.out.println("divisibleByThreeAndFive: " + divisibleByThreeAndFive.test(num));
    System.out.println("divisibleByThreeOrFive: " + divisibleByThreeOrFive.test(num));
    System.out.println("equalsToTen: " + equalToTen.test(num));

  }//from ww  w . jav a 2  s .c o  m