Predicate Interface in Java 8 with examples

This entry is part 34 of 43 in the series Java 8 Functional Interfaces

Predicate Interface is a part of the java.util.function package which is introduced in Java 8. It is an in-built Functional Interface. This function expect an input but produces a boolean value as an output. As it is a functional interface, it can be used assignment target for lambda expression or method reference. In this post, we are going to see several implementations of Predicate Interface by using different examples.

Predicate_Interface_Java8_Techndeck

 

Predicate Interface in Java 8 with Examples...!!! Click To Tweet

Look at Predicate Javadoc description below:

PredicateInterface_Signature_Java8_Techndeck

 

 

 

 

Predicate Interface contains 5 methods:

  1. test

  2. and

  3. or

  4. negate

  5. isEqual

Let’s discuss these methods:

test 

This method performs operation on the given argument and results in a boolean value.

and 

This method returns a composed predicate that represents a short-circuiting logical AND of this predicate and another. When evaluating the composed predicate, if this predicate is false, then the other predicate is not evaluated.

or 

This method returns a composed predicate that represents a short-circuiting logical OR of this predicate and another. When evaluating the composed predicate, if this predicate is true, then the other predicate is not evaluated.

negate 

This method returns a predicate that represents the logical negation of this predicate.

isEqual 

This method returns a predicate that tests if two arguments are equal.

 

Lets understand above mentioned methods thorough various examples:

Example 1. Simple Predicate

 

Example 2. Predicate Chaining with ‘and’

 

Example 3. Passing Predicate into a Function 

 

Example 4. ‘or’ with Anonymous/Lambda Predicate Implementation

 

Example 5. Predicate ‘negate’ 

 

Example 6. Predicate List Example

 

Example 7. with custom Class object (like ‘Employee’ in this case)

 

Java 8 Predicate Interface is an absolute useful addition as part of ‘Functional Interfaces’ and can serve variety of purposes. It is quite powerful as it can be used as a higher order functions through lambda functions and above examples could help you to get better idea on how to implement it.

 

Predicate Interface in Java 8 with Examples...!!! Click To Tweet

 

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Related Posts:

[wcp-carousel id=”5342″]
Series Navigation<< BiConsumer Interface in Java 8 with examplesConsumer Interface in Java 8 with examples >>

Leave a Reply

Your email address will not be published.Required fields are marked *

Facebook Twitter Instagram YouTube