Java Predicate

Java Predicate is a functional interface that is part of Java.util.function package. It was introduced in Java 8. It represents a single argument function that returns a boolean value. A Predicate takes an input and returns either true or false, depending on the condition that is specified in the function.

Using predicate to check if the string is empty:

A Predicate can be used to prevent a condition on a single object or a list of objects. For example, we can create a Predicate that checks if a given string is empty

Using multiple conditions in the predicate:

We can also use multiple predicates together using the and(), or(), and negate() methods. The and() method returns a Predicate that represents the logical AND of two Predicates, and the or() method returns a Predicate that represents the logical OR of two Predicates. The negate() method returns a Predicate that represents the logical NOT of a Predicate.

For example, we can create a Predicate that checks if a given string is not empty and has a length greater than 5:

Using predicate with the stream to filter numbers greater than 5:

The Predicate interface is commonly used with Java 8 streams to filter or select elements from a stream based on a specified condition. For example, we can use a Predicate to filter a list of integers that are greater than 5:

Output:

In this example, we first create a Predicate that checks if a given integer is greater than 5. Then we use this Predicate with the filter() method of the stream to select only the elements that satisfy the condition. Finally, we collect the filtered elements into a list.

In conclusion, the Predicate interface is a powerful tool in Java that allows us to define a condition that can be used to test a single object or a list of objects. It is widely used with Java 8 streams to filter or select elements based on a specified condition.

Leave a Reply