Predicate
A condition: a function that takes a value and returns a `boolean`.
Available since: Java 8
Syntax
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}Examples
Testing and combining conditions:
void main() {
Predicate<String> notEmpty = s -> !s.isEmpty();
Predicate<String> shortWord = s -> s.length() < 5;
IO.println(notEmpty.test(""));
IO.println(notEmpty.and(shortWord).test("java"));
IO.println(shortWord.negate().test("java"));
}Output:
false
true
falsePredicate.not() with a method reference:
void main() {
List<String> lines = List.of("a", " ", "b", "");
IO.println(lines.stream().filter(Predicate.not(String::isBlank)).toList());
}Output:
[a, b]Notes
It combines with and(), or() and negate(). Predicate.not() (Java 11) is handy for negating a method reference. It is taken by filter(), removeIf(), anyMatch(), takeWhile().
See also
- Stream.filter() — Keeps only the stream elements that match a condition.
- Collection.removeIf() — Removes all collection elements that match a condition.
- Function — A function that takes a value of type `T` and returns a value of type `R`.
Related recipes
In the tutorial
- Functional interfaces — Functional interfaces in Java: the @FunctionalInterface annotation, the standard Function, Predicate, Consumer, Supplier and combining them.