Predicate<T>
- Java course
- Advanced
- Lesson 14/82
- 5 min
Learn condition functions with Predicate<T>.
The Predicate<T> interface
Predicate<T> is a condition function that takes a T value and returns a boolean. Its single abstract method is test. It is often passed to filter in streams.
Example: Predicate<String> longWord = s -> s.length() > 5;. Then longWord.test("notebook") returns true. When you want to pass conditions around like values instead of classes, Predicate is ideal.
Combining Predicates
Predicates can be combined with logical operators. The and, or and negate methods produce new Predicates; this lets you build composite conditions.
Example: longWord.and(startsWithA).or(isEmpty). This means 'long and starts with A, or empty'. It is handy for expressing complex business rules in one line. The same works in streams: stream.filter(longWord.and(startsWithA)).
Practice Filter with a Predicate
Define a Predicate<String> that selects words longer than 5 characters. Take the list List.of("pen", "notebook", "case") into a stream, filter it, and print the count with System.out.println using count.
Starter code
import java.util.List;
import java.util.function.Predicate;
// Define a Predicate (length > 5)
// Filter and count
// Print the countSample solution
import java.util.List;
import java.util.function.Predicate;
public class PredicateExample {
public static void main(String[] args) {
Predicate<String> longWord = s -> s.length() > 5;
long count = List.of("pen", "notebook", "case").stream()
.filter(longWord)
.count();
System.out.println(count);
}
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Predicate methods
| Term | Meaning |
|---|---|
Predicate<T> |
Takes T returns boolean |
test |
Call method |
and |
And |
or |
Or |
negate |
Not |
2 Which is the call method of Predicate<T>?
- apply
- test Correct answer
- accept
- get
Explanation: test is Predicate's call method.
3 Complete the Predicate call
Predicate<String> longWord = s -> s.length() > 5;
boolean yes = longWord.____("defter");
Predicate<String> longWord = s -> s.length() > 5;
boolean yes = longWord.test("defter");
Explanation: test is Predicate's call method.