What is a method reference, and what are its forms?

8 minintermediatemethod-referencejava8lambda

Quick Answer

A method reference is shorthand syntax for a lambda that does nothing but call an existing method, using the :: operator. The four forms are: static method reference (Type::staticMethod), bound instance method reference (instance::method), unbound instance method reference (Type::instanceMethod, where the first lambda parameter becomes the receiver), and constructor reference (Type::new).

Detailed Answer

A method reference is compact syntax for a lambda whose entire body is just calling one existing method — the compiler infers the parameter list from the target functional interface, so you don't need to spell it out.

There are four forms:

1. Static method referenceType::staticMethod:

Function<String, Integer> parse = Integer::parseInt;
// equivalent to: s -> Integer.parseInt(s)

2. Bound instance method referenceinstance::method (the receiver object is already fixed):

String prefix = "Hello, ";
Function<String, String> greet = prefix::concat;
// equivalent to: s -> prefix.concat(s)

3. Unbound instance method referenceType::instanceMethod (no specific instance yet — the first lambda parameter becomes the receiver, remaining parameters are passed to the method):

Function<String, Integer> length = String::length;
// equivalent to: s -> s.length()

BiFunction<String, String, Boolean> startsWith = String::startsWith;
// equivalent to: (s, prefix) -> s.startsWith(prefix)

4. Constructor referenceType::new:

Supplier<ArrayList<String>> factory = ArrayList::new;
// equivalent to: () -> new ArrayList<>()

Function<String, StringBuilder> toBuilder = StringBuilder::new;
// equivalent to: s -> new StringBuilder(s)

Method references are purely syntactic sugar over an equivalent lambda — they compile to the same kind of invokedynamic-based construct — and are generally preferred over an explicit lambda when the lambda would do nothing but forward its arguments to an existing method, since they read more directly as "call this method" rather than restating the parameter list.