What Are Method References?
You'll learn: how method references give you a cleaner, more readable way to write lambdas that just call existing methods.
The Core Idea
Imagine you write a lambda expression like this: x -> System.out.println(x). All it does is take an input and pass it directly to an existing method. Method references let you skip the ceremony and write System.out::println instead—it's shorthand for "just call this method."
Analogy: If you need to tell someone "take each item and hand it to the cashier," you could say that whole sentence (lambda), or just point at the cashier and say "hand to them" (method reference). Both mean the same thing; one's just more direct.
When You Can Use Method References
A method reference works when your lambda's only job is to call an existing method with the parameter(s) it receives. Instead of writing the arrow syntax and explicitly passing arguments, you reference the method directly using the :: operator.
For example:
- Lambda:
(String s) -> s.toUpperCase() - Method reference:
String::toUpperCase
Both are functionally identical, but the method reference is more concise and often clearer about intent.
The Double-Colon Syntax
The :: operator separates the target (a class, object, or type) from the method name. Java infers which method to call based on the target type—the same contextual information you learned about in target typing and type inference.
Method references don't replace lambdas; they're just syntactic sugar for simple cases where a lambda would be redundant.
Key Takeaway: Method references use :: syntax to provide a shorthand for lambdas that only call an existing method, making your code cleaner and more expressive.