In Java 8 Predicate is a functional interface that is used to evaluate a condition. It takes a single input argument and returns a Boolean value (true or false).
- It belongs to the package: java.util.function
- It is a functional interface .
- It contains only one abstract method
- It is used for filtering and condition checking.
Predicate Interface Syntax :-
@FunctionalInterface
public interface Predicate {
boolean test(T t);
}
test() Method Overview :-
- Takes one input argument
- It returns:
- true → if condition is satisfied
- false → if condition fails
Example of Predicate in Java 8
- Predicate<Integer> is created to take the Integer values.
- Lambda expression i -> i > 20 checks if number is greater than 20
- test(15) method returns false because 15 is less than 20
- test(30) method returns true because 30 is greater than 20
public class PredcateTest {
public static void main(String[] args) {
Predicate pd = i -> i > 20;
System.out.println("status one :- " + pd.test(15));
System.out.println("status two :- " + pd.test(30));
}
}
Output :
status one : false
status two : true