What is a method reference in Java and when would you use it instead of a lambda?
A method reference is a shorthand like String::length for a lambda that only calls one existing method. It makes code shorter and clearer when the lambda adds nothing beyond that call.
Explain it simply
If a lambda says "take x and call x.length()", you can instead just point at the method: "use length". It is like saying "send it to the accounts department" instead of explaining each step again.
Example
import java.util.*;
List<String> cities = List.of("Pune", "Agra", "Kochi");
cities.forEach(System.out::println); // object::method
// prints: Pune
// prints: Agra
// prints: Kochi
List<Integer> lengths = cities.stream().map(String::length).toList(); // Class::instanceMethod
System.out.println(lengths); // prints: [4, 4, 5]
java.util.function.Supplier<List<String>> maker = ArrayList::new; // constructor reference
System.out.println(maker.get()); // prints: []What to say in the interview
"There are four kinds: a static method (Integer::parseInt), a method of a particular object (System.out::println), an instance method of an arbitrary object of a type (String::length), and a constructor (ArrayList::new). A method reference is just another way to supply a functional interface. I use it when the lambda would only forward its arguments; if I need extra logic, a lambda reads better."
Common mistakes
- Using a method reference with an overloaded method and getting an ambiguity error.