Guide: Java BiPredicate

Introduction

In this blog we will learn how to use BiPredicate functional interface in java.util.Function.

As we have seen in this blog Java Predicate, Predicate accepts single argument.

Similarly, BiPredicate will accepts 2 arguments and return boolean based on conditions.

BiPredicate<T, U> accepts the 2 arguments and returns boolean by performing business logic on the arguments.

BiPredicate<T, U> functional method is boolean test(T t, U u).

1
2
3
4
@FunctionalInterface
public interface BiPredicate<T, U> {
    boolean test(T t, U u);
}

There may be scenarios where we want to validate certains conditions based on 2 arguments

Example 1:

In this example we will check for upper limit for a given numbers.

Given 2 integers we will check whether 2 numbers crosses upper limit or not.

If it crosses upper limit return true or else false.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import java.util.function.BiPredicate;

public class Examples {

    public static void main(String[] args) {
        BiPredicate<Integer,Integer> checkforUpperlimit= (x,y) -> x+y> 50;

        System.out.println(checkforUpperlimit.test(10,20)); // false
        System.out.println(checkforUpperlimit.test(30,40)); // true
    }
}

Example 2

In the below example 1st argument is the string and 2nd argument is the threshold length of the string.

If length of the string is less than the threshold mentioned in the 2nd argument return true or else false.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import java.util.function.BiPredicate;

public class Examples {

    public static void main(String[] args) {
        BiPredicate<String,Integer> checkLength= (x,y) -> x.length() < y;
        System.out.println(checkLength.test("harish",10));  // true
        System.out.println(checkLength.test("this is a very long string",10)); //false
    }
}

Example 3

In the below we check if 1 string is substring of another.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import java.util.function.BiPredicate;

public class Examples {

    public static void main(String[] args) {
        BiPredicate<String,String> checkSubstring= (x,y) -> x.contains(y);
        System.out.println(checkSubstring.test("Hello World","lo"));  // true
        System.out.println(checkSubstring.test("this is a very long string","ong")); //true
    }
}

Conclusion

I hope this clarifies how to use BiPredicate<T, U> in Java.

Learn more functional interfaces

  1. Function interface
  2. Consumer interface
  3. Predicate interface
  4. BiFunction interface
  5. Supplier interface