Using Java 8 Predicate with 2 Arguments Example


The Functional Intrerface Predicate from the Java 8 java.util.function package has an abstract function test(T t) which takes in only one argument and returns a boolean value. If you have a requirement where you want Predicate to work with two arguments, then you should go for BiPredicate.

BiPredicate is a type of predicate (boolean-valued function) of two arguments. It is the two-arity specialization of Predicate.

It also has the same function called test but takes in two generic type arguments T and U.

Syntax:
    /**
     * Evaluates this predicate on the given arguments.
     *
     * @param t the first input argument
     * @param u the second input argument
     * @return: if the input arguments match the predicate,
     * otherwise false
     */

    boolean test(T t, U u);

Let's take a look at an example of how to work with two arguments/parameters with this predicate.

package org.code2care.examples;

import java.util.function.BiPredicate;

public class PredicateWithTwoArguments {

    public static void main(String... args) {

        int no1 = 10;
        int no2 = 10;
        BiPredicate<Integer, Integer> checkEqual = Integer::equals;

        if (checkEqual.test(no1, no2)) {
            System.out.println(no1 + " and " + no2 + " are equal");
        } else {
            System.out.println(no1 + " and " + no2 + " are not equal");
        }

    }
}

Output:

10 and 10 are equal

Predicate in Java

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