Memra

Method references: the four kinds

◈ 4 cards

Shorthand for lambdas that just call a method — and how each kind maps.

Method references: a cleaner lambda spelling

When a lambda does nothing but call a single method, a method reference (::) makes the intent clearer. There are exactly four kinds:

KindSyntaxEquivalent lambda
StaticInteger::parseInts -> Integer.parseInt(s)
Bound instanceSystem.out::printlns -> System.out.println(s)
Unbound instanceString::toUpperCases -> s.toUpperCase()
ConstructorArrayList::new() -> new ArrayList<>()

Static — the class provides a static method; all parameters come from the lambda:

Function<String, Integer> parse = Integer::parseInt;

Bound instance — a specific object is bound at the reference site; its method is called with the remaining parameters:

Consumer<String> print = System.out::println;  // out is the bound receiver

Unbound instance — no receiver is bound; the first lambda parameter becomes the receiver:

Function<String, String> upper = String::toUpperCase;
// equivalent: s -> s.toUpperCase()

Constructor::new creates a new instance with the remaining parameters:

Supplier<ArrayList<String>> factory = ArrayList::new;

The compiler matches the method reference to the functional interface's single abstract method by parameter and return types.

referencereceiverthe argument becomesInteger::parseIntnone — staticthe String to parseSystem.out::printlnSystem.out, bound herethe value printedString::toUpperCasethe first argumentthe receiver itselfArrayList::newnone — one is createdconstructor arguments
Bound and unbound look almost identical and behave differently. System.out::println already holds its receiver, so the argument is what gets printed; String::toUpperCase holds none, so the first argument becomes the receiver itself.
NORMAL ~/memra/learn/java-from-zero/method-references utf-8 LF