Java Predicate Interface
“The Predicate Interface takes a T-type input and checks whether the condition presented to it is met, and returns a “true or false” value. It is used for operations such as filtering and grouping.”
Let’s take a look closely Predicate Class and I added descriptions above the methods.
/*
* T input
* Return TRUE if the input argument matches the predicate otherwise * return FALSE
*/
boolean test(T t);
/*
* It combines two predicates and processes the and (&&) in
*/
logic.default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}/*
* It functions the same as 'not', returning the opposite of whatever * the result is.
*/
default Predicate<T> negate() {
return (t) -> !test(t);
}/*
* It is the same as and() but this time it is subjected to the or * operation in the logic.
*/
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}/*
* Returns a predicate that tests if two arguments are equal
* according
*/
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
/*
* Returns a predicate that is the negation of the supplied
* predicate.
* This is accomplished by returning result of the calling
* target.negate()
*/
@SuppressWarnings("unchecked")
static <T> Predicate<T> not(Predicate<? super T> target) {
Objects.requireNonNull(target);
return (Predicate<T>)target.negate();
}
Lets write some codes to try that methods
Predicate<String> predicator= s -> "Yigit".equals(s) ; System.out.println(predicator.test("Yigit"));
//Output : TrueSystem.out.println(predicator.test("Yigitt"));
//Output : False/* Add new Predicate rules */predicator = predicator.and(s -> s.length() == 6);
System.out.println(predicator.test("Yigit"));
//Output : False
predicator = predicator.or(s -> s.length() == 5); System.out.println(predicator.test("Yigit"));
//Output : TrueSystem.out.println(predicator.negate().test("Yigit"));
//Output : False
The Predicate interface also has versions that can take primitive type values.
- BiPredicate: It takes two parameters of type T and U and produces boolean value.
- IntPredicate: It takes an int value as a parameter and produces a result.
- DoublePredicate: It takes a double value as a parameter and produces a result.
- LongPredicate: It takes a long value as a parameter and produces a result.
The Predicates helps us briefly this way. Thank you for reading..