Predicate in Java 8 With Examples

In this article of Java , We are explaining Predicate in Java 8 with Examples.

Predicate, in mathematics , is simply a boolean valued function such as ‘P: V? {true, false}’. This function is the predicate on value V. This function can only return two values : either true or false.

In Java, Predicate is a functional interface. It was introduced in Java version 8. It is somewhere similar to Predicate as in Mathematics.

Let’s learn about Predicate in Java with more details :

Java 8 Predicate Introduction

Predicate was introduced in Java version 8. This interface is available under java.util.function package. It is a functional interface.

Functional interface is a special type of interface which only allows one abstract method inside its body. There are other functional interfaces in java as well similar to Predicate like Supplier , Consumer interface etc.

Predicate in Java 8 With Examples

Predicate interface , similar to Predicate in Maths , represents the boolean valued function / Predicate of an arguement.

It contains one Functional method – test(Object). Predicate interface improves the code manageability etc.

Java 8 Predicate Usage

As we learnt, Predicate in Java is a Functional interface thus we can use it as an assignment target for any lambda expression.

It will return either true or false depending on the condition of Predicate.

In Java Programming language, We can use Predicate in many scenarios such as where we are required to evaluate certain condition on a Collection of objects i.e. Similar group of objects and we can either return true or false as the result.

Below are the some of use cases for Java 8 Predicate :

  • Find the Employees getting salary greater than specific amount.
  • Orders processed at a specific time.
  • Find the Students basis on age etc.

Java 8 Predicate Methods

All the methods of Predicate in Java are essential. Let’s learn all the methods of Java 8 Predicate in detail.

1. isEqual(Object targetRef)

This method is used to return a predicate which tests if the two arguments are equal according to the method Objects.equals(Object, Object) or not.

Declaration :

static <T> Predicate<T> isEqual(Object targetRef)

Type Parameters :

T: The type of arguments to the Predicate.

Parameters :

targetRef : It is the reference of object for which the equality is compared . It can be null.

Returns :

This method returns a predicate which tests if the two arguments are equal or not according to Object class equals method.

2. and(Predicate other)

This method returns a composed Predicate. This composed predicate represents a logical AND of two predicates. At the time of evaluation of Composed Predicate , If first Predicate is false then the second Predicate is not evaluated.

Declaration :

default Predicate<T> and(Predicate<? super T> other) 

Type Parameters :

T: The type of arguments to the Predicate.

Parameters :

other : It is a predicate which will be logically-ANDed with this predicate.

Returns :

This method returns a composed predicate that represents the Logical ANDing of two Predicates (this and other).

throws:

It the other predicate is null, This method throws NullPointerException.

3. negate()

This method simply returns a predicate which is the logical negation of this predicate

Declaration :

defaultΒ Predicate<T>Β negate() 

Returns :

It returns a Predicate which represents the negation of this predicate.

4. or(Predicate other)

This method returns a composed predicate. This composed Predicate is the representation of the Logical OR of this predicate and other.

At the time of evaluation of the composed predicate, If this Predicate is true then other predicate is not even evaluated.

Declaration :

 defaultΒ Predicate<T>Β or(Predicate<? super T>Β other) 

Type Parameters :

T: The type of arguments to the Predicate.

Parameters :

other : It is a predicate which will be logically-ORed with this predicate.

Returns :

This method returns a composed predicate that represents the Logical ORing of two Predicates (this and other).

throws:

It the other is null, This method throws NullPointerException.

5. test(T t)

This method evaluates this predicate on the passed argument.

Declaration :

 booleanΒ test(TΒ t)

Parameters :

tΒ : It is the input argument 

Returns :

This method simply returns true if the Predicate matches the input argument otherwise it return false.

Java 8 Predicate : Simple Example

This below example illustrates :

  • How to create a simple Predicate in Java.
  • Create a Predicate to check the age lesser than 30.
  • Call the Predicate method to print the results.
  • Use of test() method of Predicate in Java.

import java.util.function.Predicate; 

public class PredicateExample { 
    
    //Main method
    public static void main(String[] args) 
    { 
        // Create the Predicate
        // Condition says less than 30
        Predicate<Integer> age = i -> (i < 30);  
  
        // Call the Predicate method 
        System.out.println(age.test(25));  
    } 
} 

Output :

true 

Java 8 Predicate : Predicate Chaining Example

This below example illustrates :

  • The example of Predicate Chaining.
  • Use of and() method.
  • Use of test() method.
  • Use of negate() method.

import java.util.function.Predicate; 

public class PredicateExample { 
    
    //Main method
    public static void main(String[] args) 
    { 
        // Create the Predicate
        // Condition says greater than 30
        Predicate<Integer> greaterAge = (i) -> (i > 30);  
        
        // Create the Predicate
        // Condition says lesser than 60
        Predicate<Integer> lesserAge = (i) -> (i < 60); 
        
        // Call the Predicate method to get the result -- Predicate chaining
        boolean output = greaterAge.and(lesserAge).test(50); 
        System.out.println(output); 
  
        boolean output2 = greaterAge.and(lesserAge).negate().test(50); 
        System.out.println(output2); 
        
    } 
} 

Output:

true 
false 

Java 8 Predicate : Predicate into a function Example

This below example illustrates following :

  • How to pass Predicate as an argument into the method.

import java.util.function.Predicate; 

public class PredicateExample { 
    
    //Method having Predicate 
    static void predicateFunc(int age, Predicate<Integer> pred) 
    {   
        //If predicate is true - condition i.e. age is greater than 18
        if (pred.test(age)) { 
            //System.out.println("Age " + age); 
        } 
    } 
    
    //Main method
    public static void main(String[] args) 
    { 
        //Calling the method
        predicateFunc(30, (i) -> i > 18); 
        
    } 
} 

Output:

Age 30

Java 8 Predicate : Predicate OR Example

The below example illustrates following :

  • How to use Lambda expression in Java 8 Predicate.
  • Use the OR method of Predicate in Java.
import java.util.function.Predicate; 

public class PredicateExample { 
  
    public static Predicate<String> lengthPredicate = new Predicate<String>() { 
        @Override
        public boolean test(String str) 
        { 
            return str.length() > 10; 
        } 
    }; 
  
    //Method to test the Predicate OR
    public static void predicateOrTest() 
    { 
        //Defining the Predicate 
        Predicate<String> predicateX = s -> s.contains("X"); 
      
        String otherString = "Xyz"; 
      
        boolean result = lengthPredicate.or(predicateX).test(otherString); 
      
        System.out.println(result); 
    } 
  
    //Main method 
    public static void main(String[] args) 
    { 
        //Calling the method
        predicateOrTest(); 
    } 
} 

Output :

true

Conclusion

We have covered the Java 8 Feature – Predicate complete tutorial in this article. We have covered below topics :

  • Java 8 Predicate basics.
  • Predicate usage in Java.
  • Method of Predicate in Java.
  • Multiple use cases and Examples etc.

Thanks for Reading!

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply