The predicate is a predefined functional interface in Java defined in the java.util.Function
package. It helps with manageability of code, aids in unit-testing, and provides various handy functions.
Let’s have a look at a few methods that the Java predicate provides.
test(T t)
It evaluates the predicate on the value passed to this function as the argument and then returns a boolean value. Take a look at the example below:
import java.util.function.Predicate; class testDemo { public static void main(String[] args) { Predicate<Integer> greater_than = x -> (x > 10); // calling test method of the predicate System.out.println(greater_than.test(11)); } }
isEqual(Object t)
It returns a predicate that tests if two objects are equal. Take a look at the example below:
import java.util.function.Predicate; class isEqualDemo { public static void main( String args[] ) { Predicate<String> pred = Predicate.isEqual("Educative"); System.out.println(pred.test("educative ")); } }
and(Predicate P)
It returns a composed predicate that represents a logical AND of the outputs coming from both predicates. Take a look at the example below:
import java.util.function.Predicate; class andDemo { public static void main(String[] args) { Predicate<Integer> grt_10 = x -> (x > 10); Predicate<Integer> less_100 = x -> (x < 100); // composing two predicates using and System.out.println(grt_10.and(less_100).test(60)); } }
or(Predicate P)
It returns a composed predicate that represents a logical OR of the outputs coming from both predicates. Take a look at the example below:
import java.util.function.Predicate; class andDemo { public static void main(String[] args) { Predicate<Integer> eq_10 = x -> (x == 10); Predicate<Integer> grt_20 = x -> (x > 20); // composing two predicates using and System.out.println(eq_10.or(grt_20).test(21)); } }
negate()
It returns a predicate that represents the logical negation of the respective predicate. Take a look at the example below:
import java.util.function.Predicate; class testDemo { public static void main(String[] args) { Predicate<Integer> greater_than = x -> (x > 10); // calling negate method of the predicate System.out.println(greater_than.negate().test(11)); } }
RELATED TAGS
View all Courses