A predicate is a function with a single argument and it returns a boolean value.
Predicate Interface (functional interface)
It is a functional interface with only
one abstract method that can take in any type of argument but it always should return a boolean true
or false.
interface Predicate<T> {
public boolean test(T t);
}
Because it is a functional interface, it can use lambda expression.
public class GreaterThanTwenty {
public static void main(String[] args) {
Predicate<Integer> p = i -> (i>20);
System.out.println(p.test(15));
}
}
Passing Predicate to a method
public class PredicateJoins {
public static void main(String[] args) {
Predicate<Integer> p = i -> i > 20;
int[] x = {10, 20, 30};
method1(p, x);
}
static void method1(Predicate<Integer> p, int[] x) {
for (int i : x) {
if(p.test(i)) {
System.out.println(i);
}
}
}
}
Predicate Joining
negate()
and(p)
or(p)
public class PredicateJoins {
public static void main(String[] args) {
Predicate<Integer> p1 = i -> i > 20;
Predicate<Integer> p2 = i -> i % 2 == 0;
int[] x = {10, 20, 30};
method1(p1, x);// > 20
method1(p2, x);// even number
method1(p1.negate(), x);// <= 20
method1(p1.and(p2), x);
method1(p1.or(p2), x);
}
static void method1(Predicate<Integer> p, int[] x) {
for (int i : x) {
if(p.test(i)) {
System.out.println(i);
}
}
}
}