Predicate In Java 8

“The term “PREDICATE” implies a statement that evaluates whether a value is true or false.”

Now let’s talk about the role of the predicate in Java 8,

  • Predicate is a type of Functional interface in Java
  • As mentioned, it will always return true or false
  • we know that a functional interface has only one abstract method,So Predicate has one abstract method i.e. test()
  • A predicate is in Java 8 and resides under java.util.function package
  • Based on our requirement we can override test() method by implementing the Predicate Functional Interface

Predicate Syntax

blow is the Syntax in the Java 8

@FunctionalInterface

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

Simple Predicate Example

this is sample program which will tell us number is positive or not

 Predicate<Integer> isPositiveNo=no->no>=0;

        int value= -2;
        
        if(isPositiveNo.test(value)){
            System.out.println("This is Positive No.");
        }else{
            System.out.println("This is Negative No.");
        }

// the out put will  "This is Negative No." because we have given -2 in the input

Leave a comment