Learn about Predicate Functional Interface in Java

The Predicate interface is used primarily to filter a Stream object. Using the filter() method with the Predicate interface parameter will allow us to filter the items in the Stream object to satisfy some conditions.

The content of this interface is as follows:

As a Functional Interface, the Predicate has an abstract method test(). This method takes the parameter with the generic data type, will return true or false to indicate whether the item satisfies the filter condition.

Eg:

In the above example, you can see that Java inspects all items in the Stream object for items that start with K, and then prints them.

Result:

Learn about Predicate Functional Interface in Java

In the Predicate interface we also have some default methods such as and(), or(), negate() with functions like and-and, or, negative.

With the and() method, we can aggregate many conditions to filter the data. Eg:

Result:

Learn about Predicate Functional Interface in Java

The or() method only satisfies one of the conditions. Eg:

Result:

Learn about Predicate Functional Interface in Java

The negate() method negates the condition. Eg:

Result:

Learn about Predicate Functional Interface in Java

Add Comment