Method References as Further Simplification
What you'll learn: How to replace simple lambdas with even more concise method reference syntax when the lambda just calls an existing method.
When you've converted an anonymous class to a lambda, you've already eliminated boilerplate. But sometimes lambdas can be simplified even further. If your lambda does nothing except call a single existing method, Java lets you reference that method directly using the :: operator.
The Core Idea
A method reference is shorthand for a lambda that simply delegates to an existing method. Instead of writing x -> SomeClass.someMethod(x), you can write SomeClass::someMethod. The compiler understands that you want to pass arguments directly to that method.
Think of it like giving directions: instead of saying "take this item and hand it to the checkout person" (lambda), you just point and say "checkout" (method reference). The action is the same, but more direct.
Common Patterns
Static method reference:
- Lambda:
(s) -> Integer.parseInt(s) - Method reference:
Integer::parseInt
Instance method on specific object:
- Lambda:
(s) -> myPrinter.print(s) - Method reference:
myPrinter::print
Instance method on parameter:
- Lambda:
(s) -> s.toLowerCase() - Method reference:
String::toLowerCase
When to Use Method References
Use method references when your lambda's only job is to pass its parameters to an existing method without any transformation or additional logic. If you need extra processing, stick with the lambda.
Key Takeaway: Method references (using ::) provide the most concise syntax when a lambda simply delegates to an existing method, making your code cleaner and more readable.