Method References vs Lambda Parameter Order
You'll learn: How the order of parameters in a functional interface maps to the order of arguments expected by a method reference.
When you use a method reference, Java automatically maps the functional interface's parameters to the referenced method's parameters in order. Understanding this implicit mapping is crucial for writing correct method references.
The Implicit Parameter Mapping
With lambda expressions, you explicitly see the parameter flow:
BiPredicate<String, String> lambdaVersion = (s1, s2) -> s1.equals(s2);
With method references, the mapping is implicit:
BiPredicate<String, String> refVersion = String::equals;
Here's what's happening behind the scenes:
- First parameter (
s1) becomes the object on whichequalsis called - Second parameter (
s2) becomes the argument toequals
Order Matters
The parameters must align perfectly. Consider BiFunction<T, U, R>:
BiFunction<String, Integer, String> substring = String::substring;
// Parameter 1 (String) → the object
// Parameter 2 (Integer) → the method argument
This works because substring(int) expects one int argument. The String becomes the receiving object, and the Integer becomes the method parameter.
Think of It as a Queue
Imagine parameters flowing left-to-right into the method reference. The first parameter becomes the receiver (for instance methods on arbitrary objects), and subsequent parameters fill the method's argument list in order.
Key Takeaway: Method references map functional interface parameters to method parameters sequentially—the first parameter typically becomes the object (receiver), and remaining parameters match the method's arguments in exact order. When the mapping doesn't align naturally, use an explicit lambda instead.