What is a method reference?
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Your lambda does nothing except call a method that already exists, like s -> s.length(). It feels like too much typing for so little.
A lambda that only calls one method
A method reference, such as String::length, is a short way to write a lambda that only calls one existing method.
Many lambdas do one thing: they take their input and hand it straight to an existing method. s -> System.out.println(s) gives s to println. s -> s.length() calls length on s. text -> Integer.parseInt(text) gives text to parseInt.
Example 1 · The same task as a lambda and as a method reference
import java.util.ArrayList;import java.util.List;import java.util.function.Consumer;import java.util.function.Function;
public class FirstReferenceDemo { public static void main(String[] args) { List<String> cities = new ArrayList<>(List.of("Pune", "Chennai", "Goa"));
// printing every item: lambda, then method reference cities.forEach(c -> System.out.println(c)); cities.forEach(System.out::println);
// the same objects stored in variables Consumer<String> printLambda = c -> System.out.println(c); Consumer<String> printRef = System.out::println; printLambda.accept("lambda says Delhi"); printRef.accept("reference says Delhi");
Function<String, Integer> lengthLambda = c -> c.length(); Function<String, Integer> lengthRef = String::length; System.out.println(lengthLambda.apply("Bengaluru") + " " + lengthRef.apply("Bengaluru")); }}Pune Chennai Goa Pune Chennai Goa lambda says Delhi reference says Delhi 9 9
What this code does
System.out::printlnandc -> System.out.println(c)build the sameConsumer<String>. Eachacceptcall runsprintlnwith the value it receives.String::lengthis the short form ofc -> c.length(). Both are aFunction<String, Integer>and give 9 for"Bengaluru".
In these lambdas the parameter name carries no meaning. It is only a wire from the interface method to the real method. A method reference removes the wire. It is an expression with the :: symbol that names an existing method, such as System.out::println, and Java connects the arguments for you. A method reference creates exactly the same kind of object as the lambda: an object of a functional interface. It does not call the method when it is written. The method runs later, each time the interface method (accept, apply, test, get) is called.
:: as "use this method". String::length means "use the length method of String", not "call length now".The four kinds at a glance
Every method reference has the form Something::name. What stands on the left of :: decides the kind, and each kind is a short form of one lambda shape.
Example 2 · All four kinds in one program
import java.util.ArrayList;import java.util.List;import java.util.function.Consumer;import java.util.function.Function;import java.util.function.Supplier;
public class FourKindsDemo { public static void main(String[] args) { Function<String, Integer> parse = Integer::parseInt;
Consumer<String> print = System.out::println;
Function<String, String> shout = String::toUpperCase;
Supplier<List<String>> newList = ArrayList::new;
int marks = parse.apply("87") + 5; print.accept("Marks after grace: " + marks); print.accept(shout.apply("result declared"));
List<String> toppers = newList.get(); toppers.add("Asha"); toppers.add("Ravi"); print.accept("Toppers: " + toppers); }}Marks after grace: 92 RESULT DECLARED Toppers: [Asha, Ravi]
What this code does
- The left side of
::tells you the kind: a class with a static method, a fixed object, a class whose object comes in later, ornew. - None of the four methods runs on the line where the reference is written.
parseIntruns only insideparse.apply("87"), and the list is created only bynewList.get().
The four kinds, each with the lambda it replaces:
- Static method,
ClassName::staticMethod:Integer::parseIntiss -> Integer.parseInt(s). - Bound instance method,
object::method(the object is already known):System.out::printlnisx -> System.out.println(x). - Unbound instance method,
ClassName::instanceMethod(the object comes in as the first argument):String::lengthiss -> s.length(). - Constructor,
ClassName::new:ArrayList::newis() -> new ArrayList<>().
How the compiler matches a reference
A method reference has no type of its own. Java needs a target type: the functional interface that the place expects, such as the type of the variable or the parameter of forEach. Without a target type, String::length means nothing to the compiler.
- Find the target type: the functional interface the variable or parameter expects.
- Read its abstract method: how many inputs, of which types, and what it returns.
- Look at the left of
::to know the kind: a class, an object ornew. - Check that the named method takes those inputs in that order and returns a fitting value.
Example 3 · One reference, many target types
import java.util.ArrayList;import java.util.List;import java.util.function.BinaryOperator;import java.util.function.Function;import java.util.function.IntBinaryOperator;import java.util.function.ToIntFunction;
public class TargetTypeDemo { public static void main(String[] args) { Function<String, Integer> boxedLength = String::length; ToIntFunction<String> plainLength = String::length; System.out.println(boxedLength.apply("Kochi") + " " + plainLength.applyAsInt("Kochi"));
BinaryOperator<Integer> higherBoxed = Math::max; IntBinaryOperator higherPlain = Math::max; System.out.println(higherBoxed.apply(72, 88) + " " + higherPlain.applyAsInt(72, 88));
List<Integer> runs = new ArrayList<>(List.of(45, 12, 78, 30)); runs.sort(Integer::compare); System.out.println(runs); }}5 5 88 88 [12, 30, 45, 78]
What this code does
- The same text
String::lengthbecomes aFunction<String, Integer>in one line and aToIntFunction<String>in the next. The target type decides which interface object is built. Integer::comparetakes twointvalues and returns anint, which is exactly the shape ofComparator<Integer>.compare, sosortaccepts it.
Example 4 · Mistake: a method reference with no target type
import java.util.function.Function;
public class NoTargetDemo { public static void main(String[] args) { var length = String::length; System.out.println(length); }}NoTargetDemo.java:5: error: cannot infer type for local variable length
var length = String::length;
^
(method reference needs an explicit target-type)
1 errorWhat this code does
varasks Java to take the type from the right side, but a method reference has no type of its own. Java has nothing to matchString::lengthagainst, so it stops.- Fix: give the variable a functional interface type,
Function<String, Integer> length = String::length;, or pass the reference straight to a method that expects one.
Java then reads the target's one abstract method and searches for a method that fits it. For Function<String, Integer> f = String::length; it reads Integer apply(String). The input is a String, so length is called on that String. length returns an int, and Java boxes it into the Integer that apply returns. The parameters must fit in number and in order, and the return value must fit the interface's return type. If the interface returns void, like Consumer, any return value is simply ignored. If nothing fits, or two methods fit equally well, the code does not compile.
Fix the error
Give the reference a target
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
A method reference needs an interface to turn into.
Error
RefFix.java:5: error: cannot infer type for local variable len
var len = String::length;
(method reference needs an explicit target-type)When a method reference is not possible
A method reference only replaces a lambda whose whole body is one method call that passes the lambda's parameters straight through, in the same order. Anything extra needs a lambda.
Function<String, Integer> length = s -> s.length(); // one call, same argument...Function<String, Integer> length2 = String::length; // ...so a reference worksPredicate<Integer> pass = m -> m >= 40; // compares: no method to nameFunction<String, String> first3 = s -> s.substring(0, 3); // fixed argumentFunction<String, String> clean = s -> s.trim().toUpperCase(); // two callsm -> m >= 40 compares, so it has no method to name. s -> s.substring(0, 3) adds fixed arguments. s -> s.trim().toUpperCase() makes two calls. (a, b) -> b.compareTo(a) swaps the order. These stay lambdas, and that is perfectly fine.
Example 5 · Real use: cleaning an attendance list
import java.util.ArrayList;import java.util.List;
public class AttendanceCleanDemo { public static void main(String[] args) { // names typed by different class representatives List<String> present = new ArrayList<>(List.of(" asha ", "RAVI", " meera", " ", "john "));
present.replaceAll(String::trim); present.removeIf(String::isEmpty); present.replaceAll(String::toLowerCase); present.sort(String::compareTo);
System.out.println("Present today: " + present.size()); present.forEach(System.out::println); }}Present today: 4 asha john meera ravi
What this code does
replaceAllwants aUnaryOperator<String>,removeIfwants aPredicate<String>andsortwants aComparator<String>. Each unbound reference fits because the list item becomes the object the method is called on.- Every lambda here would only have passed its parameter along, so each one reads better as a method reference: trim, drop empty entries, lower-case, sort, print.
Next step
Check your understanding
11 quick questions