Method References as Predicates
You'll learn how to turn boolean-returning methods into predicates using clean, readable method references.
The Core Idea
Any method that takes a single argument and returns a boolean can be used as a Predicate<T> through a method reference. Instead of writing a lambda like s -> s.isEmpty(), you can write the cleaner String::isEmpty. This works because the method signature matches what Predicate expects: one input, boolean output.
How It Works
When you have a method that naturally tests a condition, you can pass it directly wherever a Predicate is expected:
List<String> words = Arrays.asList("hello", "", "world", "", "java");
// Lambda version
List<String> nonEmptyLambda = words.stream()
.filter(s -> s.isEmpty())
.collect(Collectors.toList());
// Method reference version (cleaner!)
List<String> nonEmptyRef = words.stream()
.filter(String::isEmpty)
.collect(Collectors.toList());
Common Predicate Method References
Several built-in methods work perfectly as predicates:
List<String> items = Arrays.asList("apple", null, "banana", null);
// Objects::nonNull - filters out null values
List<String> nonNulls = items.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
// Objects::isNull - finds null values
long nullCount = items.stream()
.filter(Objects::isNull)
.count();
You can also combine method reference predicates with and(), or(), and negate():
Predicate<String> notEmpty = Predicate.not(String::isEmpty);
List<String> filtered = words.stream()
.filter(Objects::nonNull)
.filter(notEmpty)
.collect(Collectors.toList());
Key Takeaway: Any boolean-returning method can become a Predicate via method reference—use String::isEmpty, Objects::nonNull, or your own custom methods for cleaner, more expressive stream operations.