Method references
A method reference is a lambda that only calls an existing method. You write Class::method or instance::method instead of x -> Class.method(x).
Detailed Explanation
When a lambda's body is a single method call, the extra syntax is noise. list.forEach(s -> System.out.println(s)) is list.forEach(System.out::println). The compiler still needs a target functional interface. The reference must match that interface's abstract method: same arity after the implicit receiver, compatible types.
There are four forms.
StaticMethod:Integer::parseIntiss -> Integer.parseInt(s).instance::method:out::printlnbinds a particular object as the receiver.Class::instanceMethod:String::lengthiss -> s.length(). The first argument becomesthisinside the method.Class::new(andType[]::new) are constructor references:User::newisname -> new User(name)when the target isFunction<String, User>.
Overloads are resolved using the target type. String::valueOf could mean many methods; assigning it to Function<Object, String> picks valueOf(Object). If the match is ambiguous, the compiler asks you to write a lambda with explicit types.
You reach for a method reference when the method already says what you mean. You keep a lambda when you need extra arguments, a null check, or a cast. s -> s == null ? "" : s.trim() cannot be a reference. String::trim NPE on null.
Method references to instance methods on a class (Person::name) compose well with streams: users.stream().map(User::name). Constructor references pair with factories: list.stream().map(Order::new).toList().
The cost is the same capture rules as lambdas. this::handle captures this. A reference to a var instance (printer::print) captures that instance. Stack traces still show generated names. Prefer a named method if you need to breakpoint a non-trivial body; the reference is only a pointer to that method, which is a feature when the method is already named well.
Code Examples
import java.util.Arrays;
import java.util.List;
public class Names {
public static void main(String[] args) {
List<String> raw = Arrays.asList(" ana ", "BO");
List<String> names = raw.stream()
.map(String::trim) // s -> s.trim()
.map(String::toLowerCase)
.toList();
System.out.println(names); // prints: [ana, bo]
}
}import java.util.function.Function;
public class Ctor {
record User(String name) {}
public static void main(String[] args) {
Function<String, User> make = User::new; // name -> new User(name)
System.out.println(make.apply("Ira")); // prints: User[name=Ira]
}
}Common Gotchas
Ambiguous overloads fail to compile
pick with a cast to the functional type or write a lambda with types.