Part 09 / Topic 7 of 10
Method references
When a lambda would do nothing but call one existing method, a method reference (::) says the same thing more directly, without a throwaway parameter name. There are four shapes.
| Shape | Example | Equivalent lambda |
|---|---|---|
| Static method | MethodReferences::shout |
text -> shout(text) |
| Instance method on a particular object | prefix::concat |
city -> prefix.concat(city) |
| Instance method on an arbitrary object of a type | String::length |
city -> city.length() |
| Constructor | City::new |
(name, pop) -> new City(name, pop) |
The third shape is the one that surprises people the first time: String::length looks like it has no object to call length() on, but the stream element supplied by map becomes the receiver of the call.
Function<String, Integer> lengthRef = String::length;
cities.stream().map(lengthRef).toList(); // [4, 5, 7]
== 1. Static method reference: ClassName::staticMethod ==
PUNE!
== 2. Instance method on a PARTICULAR object: instance::method ==
City: Pune
== 3. Instance method on an ARBITRARY object of a type: ClassName::instanceMethod ==
lengths: [4, 5, 7]
== 4. Constructor reference: ClassName::new ==
City[name=Pune, populationLakh=71], isMetro: true
Pune, Maharashtra
A full stream pipeline usually reads as a chain of shape-3 method references:
cityObjects.stream()
.filter(City::isMetro)
.map(City::name)
.map(String::toUpperCase)
.toList(); // [PUNE, DELHI]
Prefer a method reference over a lambda whenever the lambda's whole body is "call one existing method" — it is shorter and names the exact method being called.
Full program: examples/MethodReferences.java.
Done here? The practice set for Part 9 — including the solutions — is on the part page.