Method References in filter
You'll learn how to replace verbose lambda expressions in filter() operations with cleaner, more concise method references.
When you learned about lambda expressions with filter(), you passed predicates like person -> person.isActive() or str -> str.isEmpty(). Java provides a shorthand notation called method references that makes these predicates even more readable when the lambda simply calls a single method.
The Core Idea
A method reference is a compact way to refer to an existing method. When your lambda expression only invokes one method on its parameter, you can replace it with a method reference using the :: operator.
Instead of:
list.stream()
.filter(str -> str.isEmpty())
You can write:
list.stream()
.filter(String::isEmpty)
Both do exactly the same thing, but the method reference version eliminates the repetition of the parameter name.
Common Method Reference Patterns in filter
Instance methods on the parameter:
// Lambda: person -> person.isActive()
persons.stream().filter(Person::isActive)
// Lambda: str -> str.startsWith("A")
strings.stream().filter(str -> str.startsWith("A")) // can't use method reference here (has argument)
Static method predicates:
// Lambda: str -> Objects.nonNull(str)
list.stream().filter(Objects::nonNull)
When to Use Method References
Method references work best when your lambda only passes its parameter directly to a method without additional logic. If you need to pass extra arguments or combine conditions, stick with lambda expressions.
Key Takeaway: Method references with :: provide a cleaner alternative to lambdas when filtering by calling a single no-argument method, making your stream pipelines more readable and concise.