Java Predicate

In this article, we’ll talk about Java Predicate, which is a Functional Interface. A Functional Interface is one that contains exactly one abstract method.

Java Predicate

java-predicate-interface
Remember predicate from Math class in school? Yeah, something like a function that takes in a value and returns true or false.

In Java 8, java.util.function.Predicate was introduced that behaves the same way and can be used as an assignment target in lambda expressions and functional interfaces. The functional method of Predicate is test(Object).

java-functional-interface-predicate-1

Java Predicate Example

Let’s consider that we have a class Apple:

Now if we have a condition to get the apples whose weight is above 150 grams, we can write a Predicate for it as below:

Now, we can use this predicate in filter(), to filter a list of apples by the condition in this predicate.

Let’s add a method filterApples() to the ApplePredicates class:

We can call this and get the results as below in a main method:

Output:

With java 8 lambda expressions, we can do it simply as below:

Or, if we don’t want to define our own method, we can also use the default filter method and write it as:

Java 8 Predicate Methods

Let’s now go through the methods available for Predicate:

  1. default Predicate and(Predicate other)

    Returns a composed predicate that represents a logical AND of two predicates. When evaluating the composed predicate, if this predicate is false, then the other predicate is not evaluated.

    To understand this, let’s add another predicate in the ApplePredicates class:

    Now we can apply the and() function if we want to get a predicate for apple to be green and weight above or equal to 150 grams.

    This will give the following output:

    Similarly, we have or() method to do the short-circuiting, logical ORing of two predicates.

  2. default Predicate negate()

    Returns a predicate that represents the logical negation of this predicate.

    Let’s say we want the Predicate to get apples that are not green. We already have one predicate that checks for Apple to be green, so we can negate it.

    The output will be:

  3. boolean test(T t)

    Evaluates this predicate for the given argument. In our case, we can pass in an Apple object to check if this predicate returns true or false for that apple.

    Output:

  4. static Predicate isEqual(Object targetRef)

    Returns a predicate that tests if two arguments are equal according to Objects.equals() method.

    Consider we have overridden the equals() method for Apple class:

    Now, let’s say we have an Apple, which has standard color and weight. Then we can get a Predicate, that will test if the given apple is standard or not.

    This will output:

That’s it for Java Predicate functional interface.

Reference: API Doc

By admin

Leave a Reply