Predicate and BiPredicate in Java

Understanding boolean-valued functions in Java

Photo by Jonas Jacobsson on Unsplash

Introduction

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 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.
Wikipedia

Predicate

is a functional interface in Java that accepts exactly one input and can return a value. Before going into it, we first need to understand the Functional Interface.

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.

Example

Let's create the class with the fields , , , , 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 method to filter the employees based on the predicate's result.

Output

Male and age greater than 25
Id: 2, Name: Steve Rogers, Age: 28, Gender: MALE, Role: MANAGER
Female and Manager
Id: 3, Name: Natasha Romanoff, Age: 23, Gender: FEMALE, Role: MANAGER

Predicate Composition

Multiple predicates can be composed together to form a chain of predicates. The composition is done with built-in methods. , , and .

and()

Returns only if all the predicates return, else . It is equivalent to logical AND.

or()

Returns if any of the predicates return, else . It is equivalent to logical OR.

negate()

Returns if the predicate returns and vice versa. It is equivalent to logical NOT.

isEqual()

Returns a predicate that checks if two values are equal. The equality is decided using method.

Output

and() operation
true
false
or() operation
true
true
negate() operation
false
isEquaL() operation
true

BiPredicate

is a functional interface in Java that accepts two inputs and can return a value. It is similar to the interface. The only difference is that it takes two inputs instead of one.

Output

10 divisible by 2: true
5 divisible by 3: false
8 divisible by 4: true

Conclusion

  • is a functional interface in Java that accepts a single input and can return a boolean value.
  • is a functional interface in Java that accepts two inputs and can return a boolean value.
  • and are usually used to apply in a filter for a collection of objects.

Thank you 🤘

To know more about me, visit ganeshkumarm.me