Java Reference
In-Depth Information
Using the Predicate<T> Interface
A predicate represents a condition that is either true or false for a given input. The
Predicate
interface contains the
following default and static methods that let you compose a predicate based on other predicates using logical
NOT
,
AND
, and
OR
.
default Predicate<T> negate()
•
default Predicate<T> and(Predicate<? super T> other)
•
default Predicate<T> or(Predicate<? super T> other)
•
static <T> Predicate<T> isEqual(Object targetRef)
The
negate()
method returns a
Predicate
that is a logical negation of the original predicate. The
and()
method
returns a short-circuiting logical
AND
predicate of this predicate and the specified predicate. The
or()
method returns
a short-circuiting logical
OR
predicate of this predicate and the specified predicate. The
isEqual()
method returns
a predicate that tests if the specified
targetRef
is equal to the specified argument for the predicate according to
Objects.equals(Object o1, Object o2)
; if two inputs are
null
, this predicate evaluates to true. You can chain the
calls to these methods to create complex predicates. The following snippet of code shows some examples of creating
and using predicates:
•
// Create some predicates
Predicate<Integer> greaterThanTen = x -> x > 10;
Predicate<Integer> divisibleByThree = x -> x % 3 == 0;
Predicate<Integer> divisibleByFive = x -> x % 5 == 0;
Predicate<Integer> equalToTen = Predicate.isEqual(null);
// Create predicates using NOT, AND, and OR on other predciates
Predicate<Integer> lessThanOrEqualToTen = greaterThanTen.negate();
Predicate<Integer> divisibleByThreeAndFive = divisibleByThree.and(divisibleByFive);
Predicate<Integer> divisibleByThreeOrFive = divisibleByThree.or(divisibleByFive);
// Test the predicates
int num = 10;
System.out.println("Number: " + num);
System.out.println("greaterThanTen: " + greaterThanTen.test(num));
System.out.println("divisibleByThree: " + divisibleByThree.test(num));
System.out.println("divisibleByFive: " + divisibleByFive.test(num));
System.out.println("lessThanOrEqualToTen: " + lessThanOrEqualToTen.test(num));
System.out.println("divisibleByThreeAndFive: " + divisibleByThreeAndFive.test(num));
System.out.println("divisibleByThreeOrFive: " + divisibleByThreeOrFive.test(num));
System.out.println("equalsToTen: " + equalToTen.test(num));
Number: 10
greaterThanTen: false
divisibleByThree: false
divisibleByFive: true
lessThanOrEqualToTen: true
divisibleByThreeAndFive: false
divisibleByThreeOrFive: true
equalsToTen: false