Predicate and BiPredicate in Java
Understanding boolean-valued functions in Java
In Mathematics, a predicate is a boolean-valued function that returns 1or 0, i.e., true or false. Java leveraged the mathematical concept of the predicate and introduced the
Predicate interface in Java 8.
A Boolean-valued function is a function of the type f : X → B, where X is an arbitrary set and where B is a Boolean domain, whose elements are interpreted as logical values, for example, 0 = false and 1 = true.
Predicate is a functional interface in Java that accepts exactly one input and can return a
boolean value. Before going into it, we first need to understand the Functional Interface.
A functional interface is an interface that contains exactly one abstract method. It is also called Single Abstract Method (SAM) Interfaces. In Java, an interface is made functional by annotating it with
We know that predicate accepts an input and returns a boolean value. But where is it used? The predicate can be used wherever a boolean output is expected—Eg. Stream’s filter method.
Let's create the
Employee class with the fields
gender , and
Now we want to filter the employees based on the below use cases.
- Employees who are Male and age greater than 25
- Employees who are Female and are Managers.
We will create two predicates for the above use cases.
We can pass the above predicates to the
filter() method to filter the employees based on the predicate's result.
Male and age greater than 25
Id: 2, Name: Steve Rogers, Age: 28, Gender: MALE, Role: MANAGERFemale and Manager
Id: 3, Name: Natasha Romanoff, Age: 23, Gender: FEMALE, Role: MANAGER
Multiple predicates can be composed together to form a chain of predicates. The composition is done with built-in methods.
true only if all the predicates return, else
false. It is equivalent to logical AND.
true if any of the predicates return, else
false. It is equivalent to logical OR.
true if the predicate returns
false and vice versa. It is equivalent to logical NOT.
Returns a predicate that checks if two values are equal. The equality is decided using
BiPredicate is a functional interface in Java that accepts two inputs and can return a
boolean value. It is similar to the
Predicate interface. The only difference is that it takes two inputs instead of one.
10 divisible by 2: true
5 divisible by 3: false
8 divisible by 4: true
Predicateis a functional interface in Java that accepts a single input and can return a boolean value.
BiPredicateis a functional interface in Java that accepts two inputs and can return a boolean value.
BiPredicateare usually used to apply in a filter for a collection of objects.
Thank you 🤘
To know more about me, visit ganeshkumarm.me