π What is a Predicate?
AΒ Predicate in Java is a functional interface that represents a boolean-valued function (i.e., it returns true or false) for a single input.
β Used mainly in filtering, validations, and conditional logic, especially in Streams and Lambdas.
π¦ Predicate Interface Declaration
-
Itβs in the package:
java.util.function.Predicate
π§ͺ Basic Example
π Using Predicate with Streams
π Predicate Methods
| Method | Description | Example |
|---|---|---|
test(T t) |
Returns true or false
|
isEven.test(4) β true
|
and(Predicate other) |
Combines two predicates with logical AND | isEven.and(gtTen) |
or(Predicate other) |
Combines with logical OR | isEven.or(gtTen) |
negate() |
Reverses the condition | isEven.negate() |
isEqual(Object o) |
Static method to check equality | Predicate.isEqual("test") |
π§ Example with and():
β Summary
| Feature | Value |
|---|---|
| Type | Functional Interface |
| Package | java.util.function |
| Method | boolean test(T t) |
| Use Cases | Filters, validations, conditions |
| Lambda-Friendly | β Yes |