Predicate Interface is a part of the java.util.function package which is introduced in Java 8. It is an in-built Functional Interface. This function expect an input but produces a boolean value as an output. As it is a functional interface, it can be used assignment target for lambda expression or method reference. In this post, we are going to see several implementations of Predicate Interface by using different examples.

Predicate_Interface_Java8_Techndeck

Predicate Interface in Java 8 with Examples...!!! Share on X

Look at Predicate Javadoc description below:

PredicateInterface_Signature_Java8_Techndeck

Predicate Interface contains 5 methods:

  1. test

  2. and

  3. or

  4. negate

  5. isEqual

Let’s discuss these methods:

test 

This method performs operation on the given argument and results in a boolean value.

boolean test(T t);

and 

This method returns a composed predicate that represents a short-circuiting logical AND of this predicate and another. When evaluating the composed predicate, if this predicate is false, then the other predicate is not evaluated.

default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

or 

This method returns a composed predicate that represents a short-circuiting logical OR of this predicate and another. When evaluating the composed predicate, if this predicate is true, then the other predicate is not evaluated.

default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

negate 

This method returns a predicate that represents the logical negation of this predicate.

default Predicate<T> negate() {
        return (t) -> !test(t);
    }

isEqual 

This method returns a predicate that tests if two arguments are equal.

static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }

Lets understand above mentioned methods thorough various examples:

Example 1. Simple Predicate

import java.util.function.Predicate;

public class PredicateInterfaceJava8Example1 {

    public static void main(String[] args) {

        System.out.println("Predicate Interface - Java 8 - Example : Simple Predicate");

        Predicate <Integer> p = i -> i == 10;

        System.out.println("Is number matching: " + p.test(5));

    }

}

Example 2. Predicate Chaining with ‘and’

import java.util.function.Predicate;

public class PredicateInterfaceJava8Example2 {

    public static void main(String[] args) {

        System.out.println("Predicate Interface - Java 8 - Example : Predicate Chaining");

        Predicate <Integer> valueNotMatches10 = i -> i != 10;

        Predicate <Integer> valueGreatedThan5 = i -> i > 5;

        //Predicate chaining : Example with 'and' predicate
        boolean result = valueNotMatches10.and(valueGreatedThan5).test(10);

        System.out.println(result);

    }

}

Example 3. Passing Predicate into a Function 

import java.util.function.Predicate;

public class PredicateInterfaceJava8Example3 {

    public static void main(String[] args) {

        System.out.println("Predicate Interface - Java 8 - Example : Passing Predicate into a Function");

        Predicate <Integer> p = i -> i == 10;

        checkIfValueMatches(5, p);

    }

    private static void checkIfValueMatches(int i, Predicate <Integer> p) {
        System.out.println("Does value matching: " + p.test(i));
    }

}

Example 4. ‘or’ with Anonymous/Lambda Predicate Implementation

import java.util.function.Predicate;

public class PredicateInterfaceJava8Example4 {

    public static void main(String[] args) {

        System.out.println("Predicate Interface - Java 8 - Example : OR & Anonymous/Lambda Predicate Implementations");

        //Predicate anonymous implementation
        Predicate <String> startsWithSpecificString = new Predicate <String> () {
            @Override
            public boolean test(String t) {
                return t.startsWith("is");
            }
        };

        //Predicate lambda implementation
        Predicate <String> containsSpecificString = s -> s.contains("dur");

        //OR condition
        boolean result = startsWithSpecificString.or(containsSpecificString).test("isha durani");

        System.out.println(result);

    }

}

Example 5. Predicate ‘negate’ 

import java.util.function.Predicate;

public class PredicateInterfaceJava8Example7 {

    public static void main(String[] args) {

        Predicate <String> predicate = s -> s.equals("Hello Predicate");

        //NEGATE operation
        Predicate <String> predicateNegate = predicate.negate();

        System.out.println(predicateNegate.test("Hello Predicate"));

    }
}

Example 6. Predicate List Example

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class PredicateInterfaceJava8Example5 {

    public static void main(String[] args) {

        System.out.println("Predicate Interface - Java 8 - Example : Predicate List Example\n");

        Predicate <List<Integer>> listPredicateContains5 = a -> a.contains(5);

        List <Integer> l = new ArrayList <Integer> ();

        l.add(19);
        l.add(4);
        l.add(83);
        l.add(5);
        l.add(63);

        checkIfValuePresentInList(l, listPredicateContains5);

    }

    public static void checkIfValuePresentInList(List <Integer> list, Predicate <List<Integer>> p) {

        if (p.test(list)) {
            System.out.println("Success: List contains the expected value which is number 5");
        } else {
            System.out.println("Failure: List doens't contains the expected value which is number 5");
        }

    }

}

Example 7. with custom Class object (like ‘Employee’ in this case)

import java.util.function.Predicate;

public class PredicateInterfaceJava8Example6 {

    public static void main(String[] args) {

        System.out.println("Predicate Interface - Java 8 - Example : Predicate Custom Class Object Example\n");

        Predicate <Employee> employeePredicate = p -> p.getAge() > 50;

        Employee e1 = new Employee(15, "Tom Marks");
        Employee e2 = new Employee(6, "Tom Marks");
        Employee e3 = new Employee(88, "Tom Marks");

        System.out.println("Doesn age of First Employee greater than 50? : " + employeePredicate.test(e1));
        System.out.println("Doesn age of Second Employee greater than 50? : " + employeePredicate.test(e2));
        System.out.println("Doesn age of Third Employee greater than 50? : " + employeePredicate.test(e3));
    }

}


class Employee {

    int age;
    String name;

    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public Employee(int age, String name) {
        this.age = age;
        this.name = name;
    }
}

Java 8 Predicate Interface is an absolute useful addition as part of ‘Functional Interfaces’ and can serve variety of purposes. It is quite powerful as it can be used as a higher order functions through lambda functions and above examples could help you to get better idea on how to implement it.

Predicate Interface in Java 8 with Examples...!!! Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts