Deep Dive into Java 8 Predicate Interface


Predicate in Java

Predicate is a Functional Interface (an Interface with only one abstract method) that was introduced in Java 8 in the java.util.function package.

MethodDescriptionReturn TypeExceptionsInput TypeAdded in JDK
test(T t)Evaluates this predicate on the given argument.booleanTJava 8
and(Predicate<? super T> other)Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.Predicate<T>NullPointerException if other is nullTJava 8
negate()Returns a predicate that represents the logical negation of this predicate.Predicate<T>N/AJava 8
or(Predicate<? super T> other)Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.Predicate<T>NullPointerException if other is nullTJava 8
isEqual(Object targetRef)Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).Predicate<T>TJava 8
not(Predicate<? super T> target)Returns a predicate that is the negation of the supplied predicate.Predicate<T>NullPointerException if target is nullTJava 11

Note: and(), negate(), or(), not() and isEqual() are all default methods.


The test() is the abstract method that returns a boolean by predicting whether the performed condition is true or not for the provided generic type argument T.


Example:

    public static void main(String[] args) {

        Predicate<Integer> evenOrOdd = num -> num % 2 == 0;

        int testNumberForEvenOdd = 12;
        boolean isEven = evenOrOdd.test(testNumberForEvenOdd);
        System.out.println(testNumberForEvenOdd + " is Even: " + isEven);

    }

Output:

12 is Even: true



Official Java 8 Predicate Documentation:

  1. test(T t): Evaluates this predicate on the given argument.

  2. and(Predicate<? super T> other): Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.

  3. negate(): Returns a predicate that represents the logical negation of this predicate.

  4. or(Predicate<? super T> other): Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.

  5. isEqual(Object targetRef): Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).

  6. not(Predicate<? super T> target): Returns a predicate that is the negation of the supplied predicate.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap