JAVA-230 · Lesson 2 of 12 · 20 min

Method references

▶ Video coming soon A video version of this lesson is on the way.

Hamza came back on Wednesday, September 22, with his list of lambdas that had grown too long, and with a second list he had not been asked for: lambdas that did nothing except call one method, such as p -> p.code() and s -> System.out.println(s). "Those ones bother me," he said. "The lambda just passes its argument straight along." Ingrid said that was exactly the right thing to be bothered by. Java has a shorter way to write a lambda whose whole job is to call an existing method: a method reference, written with a double colon, such as Part::code or System.out::println. It reads as "use this method here", and it is the second half of the answer to long lambdas: move the logic into a named method, then refer to it.

From lambda to method reference

A method reference is not a new kind of object. Like a lambda, it becomes an instance of the functional interface it is assigned to, and the compiler checks that the method's parameters and return type fit that interface's single method. The difference is only in how you write it. Where a lambda says how to call the method, a reference just names it and lets the compiler supply the arguments in order.

Lambdas and the method references that replace them
LambdaMethod referenceKind
s -> Integer.parseInt(s)Integer::parseIntStatic method
s -> System.out.println(s)System.out::printlnInstance method of a particular object
p -> p.code()Part::codeInstance method of any object of a type
(a, b) -> a.compareTo(b)String::compareToInstance method of any object, two arguments
() -> new ArrayList<>()ArrayList::newConstructor
n -> new int[n]int[]::newArray constructor

The four kinds look alike, so it helps to ask one question for each reference: where does the object come from? For a static method there is no object. For a particular object, the object is written before the double colon and fixed when the reference is created. For any object of a type, the object is the first argument passed in when the interface's method is called. For a constructor, the object is the new one being made.

Four rows, one per kind of method reference: Integer::parseInt is a static method with no object; System.out::println is a particular object fixed when the reference is made; Part::code is any object of a type, which is the first argument passed in; Part::new is a constructor, where a new object is made.
For each kind of method reference, ask where the object comes from.

Hamza copied the figure onto an index card and kept it beside the keyboard for the first few weeks. When a reference did not compile, the card usually explained why. Part::code used where a Supplier<String> was expected fails because there is no first argument to supply the Part, while part::code, written with a particular part in a variable, fits a Supplier<String> perfectly. The two look almost the same on the page, but one takes its object from the argument list and the other has already captured it.

Static methods and particular objects

A static method reference such as Integer::parseInt fits any functional interface that passes the right arguments and expects the right result: here, a Function<String, Integer> or a ToIntFunction<String>. A reference to an instance method of a particular object, such as System.out::println or formatter::format, captures that object when the reference is made. If the object is a variable, the variable must be effectively final, for the same reason as with lambdas.

Java Example · Main.java
import java.util.*;
import java.util.function.*;

public class Main {
    static boolean isTubeCode(String code) {
        return code.startsWith("TUBE-");
    }

    static class LabelPrinter {
        private final String shop;
        private int printed = 0;
        LabelPrinter(String shop) { this.shop = shop; }
        void print(String code) {
            printed++;
            System.out.println(shop + " | " + code);
        }
        int printed() { return printed; }
    }

    public static void main(String[] args) {
        List<String> counts = List.of("3", "14", "2", "25");
        ToIntFunction<String> parse = Integer::parseInt;     // static method
        int total = 0;
        for (String c : counts) total += parse.applyAsInt(c);
        System.out.println("Total parts counted: " + total);

        Predicate<String> tube = Main::isTubeCode;            // our own static method
        System.out.println("TUBE-700x25 is a tube: " + tube.test("TUBE-700x25"));

        LabelPrinter printer = new LabelPrinter("Second Gear");
        Consumer<String> label = printer::print;              // a particular object
        List.of("TUBE-700x25", "CHAIN-11", "BELL").forEach(label);
        System.out.println("Labels printed: " + printer.printed());
    }
}
Output
Total parts counted: 44
TUBE-700x25 is a tube: true
Second Gear | TUBE-700x25
Second Gear | CHAIN-11
Second Gear | BELL
Labels printed: 3

What this code does

Integer::parseInt and Main::isTubeCode are static method references, so no object is involved and each call simply passes the string along. printer::print is bound to one LabelPrinter, which is why all three labels carry the shop name and its counter ends at 3. List.forEach takes a Consumer, so the reference can be passed straight to it.

Instance methods of any object

The third kind surprises most people. Part::code names an instance method, code(), without saying which part. When the interface's method is called, its first argument becomes the object the method is called on, and any further arguments become the method's arguments. So Part::code fits Function<Part, String>, and String::compareToIgnoreCase fits Comparator<String>, whose method takes two strings and calls the first one's compareToIgnoreCase with the second. This kind is the one you will write most often with streams and comparators, because the elements being processed are the objects.

Java Example · Main.java
import java.util.*;
import java.util.function.*;

public class Main {
    record Part(String code, String supplier, int quantity) {
        boolean isLow() { return quantity < 5; }
    }

    public static void main(String[] args) {
        List<Part> parts = new ArrayList<>(List.of(
            new Part("pad-road", "Velotek", 14),
            new Part("Chain-11", "Kessler", 2),
            new Part("TUBE-700x25", "Velotek", 3),
            new Part("bell", "Kessler", 25)));

        Function<Part, String> code = Part::code;
        Predicate<Part> low = Part::isLow;
        BiFunction<String, String, Boolean> sameText = String::equalsIgnoreCase;

        System.out.println("First code: " + code.apply(parts.get(0)));
        System.out.println("Second part low? " + low.test(parts.get(1)));
        System.out.println("bell = BELL? " + sameText.apply("bell", "BELL"));

        List<String> codes = new ArrayList<>();
        for (Part p : parts) codes.add(code.apply(p));
        codes.sort(String::compareToIgnoreCase);
        System.out.println("Sorted, ignoring case: " + codes);

        parts.sort(Comparator.comparing(Part::supplier).thenComparing(Part::quantity));
        for (Part p : parts) System.out.println(p.supplier() + " " + p.quantity() + " " + p.code());
    }
}
Output
First code: pad-road
Second part low? true
bell = BELL? true
Sorted, ignoring case: [bell, Chain-11, pad-road, TUBE-700x25]
Kessler 2 Chain-11
Kessler 25 bell
Velotek 3 TUBE-700x25
Velotek 14 pad-road

What this code does

Part::code and Part::isLow take a part as their argument and call the method on it, so they fit Function and Predicate. String::compareToIgnoreCase fits Comparator<String> because the first string calls the method with the second as its argument, which sorts the mixed-case codes alphabetically. Comparator.comparing with two method references reads almost like the sentence it means: by supplier, then by quantity.

When a reference could fit more than one way, the compiler may reject it as ambiguous. A common case is Integer::toString, which could be the static toString(int) or the instance method toString() on an Integer. Writing the lambda, n -> Integer.toString(n), removes the doubt. A method reference is shorthand, never a requirement.

Constructor references

ClassName::new refers to a constructor. Which constructor depends on the interface: with a Supplier it is the no-argument constructor, with a Function it is the one-argument constructor, and with a BiFunction the two-argument one. Records make this especially handy, because a record's canonical constructor can turn the parts of a line of data straight into an object. Array constructors such as String[]::new are used to turn a stream back into an array, as you will see in lesson 3.

Java Example · Main.java
import java.util.*;
import java.util.function.*;

public class Main {
    record Shelf(String name) { }
    record Part(String code, int quantity) { }

    public static void main(String[] args) {
        Supplier<List<String>> newList = ArrayList::new;
        Function<String, Shelf> shelf = Shelf::new;
        BiFunction<String, Integer, Part> part = Part::new;
        IntFunction<String[]> array = String[]::new;

        List<String> order = newList.get();
        order.add("TUBE-700x25");
        System.out.println("New list: " + order);
        System.out.println("Shelf: " + shelf.apply("B-3"));
        System.out.println("Part: " + part.apply("CHAIN-11", 2));

        String[] slots = array.apply(3);
        System.out.println("Array length: " + slots.length + ", first slot: " + slots[0]);

        List<Shelf> shelves = new ArrayList<>();
        for (String name : List.of("A-1", "A-2", "B-3")) shelves.add(shelf.apply(name));
        System.out.println(shelves);
    }
}
Output
New list: [TUBE-700x25]
Shelf: Shelf[name=B-3]
Part: Part[code=CHAIN-11, quantity=2]
Array length: 3, first slot: null
[Shelf[name=A-1], Shelf[name=A-2], Shelf[name=B-3]]

What this code does

ArrayList::new fits Supplier, so it uses the constructor with no arguments, while Shelf::new and Part::new fit Function and BiFunction and pick the record constructors with one and two components. String[]::new fits IntFunction and builds an array of the requested length, filled with null. The last loop shows the usual use: turning raw values into objects with one reference.

Choosing between a lambda and a reference

Use a method reference when it is shorter and clearer, which is when the lambda would only pass its arguments to one method in the same order. Keep the lambda when it does anything else: adds a constant, reorders arguments, calls two methods or needs a small expression such as p -> p.quantity() * 2. And when a lambda has grown long, do not try to squeeze it into a reference; give the logic a name with a private method, then refer to the method. That last step is what turned Hamza's long lambdas into one-word references.

Java Example · Main.java
import java.util.*;
import java.util.function.*;

public class Main {
    record Booking(int number, String bike, int days, boolean returnedLate) { }

    // The long lambda from last week, given a name
    static String reminder(Booking b) {
        String when = b.days() == 1 ? "tomorrow" : "in " + b.days() + " days";
        String extra = b.returnedLate() ? " Please return it on time this time." : "";
        return "Booking " + b.number() + ": your " + b.bike() + " is due back " + when + "." + extra;
    }

    public static void main(String[] args) {
        List<Booking> bookings = List.of(
            new Booking(1041, "CITY-2", 1, false),
            new Booking(1042, "CARGO-1", 3, true));

        Function<Booking, String> asLambda = b -> reminder(b);   // works, but just passes b along
        Function<Booking, String> asRef = Main::reminder;        // says the same thing more briefly
        Function<Booking, Integer> twice = b -> b.days() * 2;    // not a plain call: keep the lambda

        for (Booking b : bookings) {
            System.out.println(asRef.apply(b));
        }
        System.out.println("Same text: " + asLambda.apply(bookings.get(0)).equals(asRef.apply(bookings.get(0))));
        System.out.println("Double length of 1042: " + twice.apply(bookings.get(1)));
    }
}
Output
Booking 1041: your CITY-2 is due back tomorrow.
Booking 1042: your CARGO-1 is due back in 3 days. Please return it on time this time.
Same text: true
Double length of 1042: 6

What this code does

The reminder logic that used to be a long lambda is now a static method with a name, so the reference Main::reminder is all the calling code needs. The lambda b -> reminder(b) produces the same text, as the comparison shows, but the reference is shorter. The doubling rule is not a plain call to one method, so it stays a lambda.

Method references also make stack traces and debuggers easier to follow, because the frame shows the named method, Main.reminder, rather than a generated lambda name. Ingrid's rule of thumb for the shop's code was simple: if you can read the reference aloud as a sentence, use it.

Try it yourself

Replace the lambdas

Replace each of the three lambdas with a method reference: toUpper should use String::toUpperCase, parse should use Integer::parseInt and show should use System.out::println. Don't change anything else.

The program prints the same lines either way, so the check is that it still prints CHAIN-11, TUBE-700X25 and Total: 7. Make the change, then run it to confirm.

import java.util.*;
import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        Function<String, String> toUpper = s -> s.toUpperCase();
        Function<String, Integer> parse = s -> Integer.parseInt(s);
        Consumer<String> show = s -> System.out.println(s);
        for (String code : List.of("chain-11", "tube-700x25")) show.accept(toUpper.apply(code));
        int total = 0;
        for (String n : List.of("2", "5")) total += parse.apply(n);
        show.accept("Total " + total);
    }
}

Try it yourself

Sort the rack

Tamsin's repair rack is a list of Repair records. Sort it with Comparator.comparing and method references: first by bay (alphabetical), then by minutes from **longest to shortest**.

Then print each repair as bay minutes bike, for example A 90 CITY-2.

import java.util.*;

public class Main {
    record Repair(String bike, String bay, int minutes) { }

    public static void main(String[] args) {
        List<Repair> rack = new ArrayList<>(List.of(
            new Repair("CITY-2", "A", 90), new Repair("CARGO-1", "B", 45),
            new Repair("TANDEM-1", "A", 120), new Repair("CITY-4", "B", 30),
            new Repair("CITY-3", "A", 20)));
        // sort the rack here
        for (Repair r : rack) System.out.println(r.bay() + " " + r.minutes() + " " + r.bike());
    }
}

Common mistakes

  • MistakeWriting p -> p.code() everywhere.

    InsteadWrite Part::code when the lambda only passes its argument to one method.

  • MistakeForcing a reference where the lambda does more than one call.

    InsteadKeep the lambda for expressions such as p -> p.quantity() * 2.

  • MistakeNot knowing which object a reference uses.

    InsteadAsk where the object comes from: none (static), fixed (particular object), first argument (any object) or new (constructor).

  • MistakeFighting an ambiguous reference such as Integer::toString.

    InsteadWrite the lambda instead; references are only shorthand.

  • MistakeSqueezing long logic into a lambda.

    InsteadMove it into a named private method and refer to that method.

Summary and key terms

  • A method reference is shorthand for a lambda that only calls one existing method, written with a double colon.
  • There are four kinds: a static method (Integer::parseInt), an instance method of a particular object (System.out::println), an instance method of any object of a type, where the first argument becomes the object (Part::code, String::compareToIgnoreCase), and a constructor (ArrayList::new, Part::new, String[]::new).
  • Which method or constructor is used depends on the functional interface the reference is assigned to.
  • References read well with Comparator.comparing and thenComparing.
  • Use a reference when it is shorter and clearer, keep a lambda when it does anything beyond passing arguments along, and give long logic a name so it can be referred to.
Method reference
A short way to write a lambda that only calls one existing method, written Type::method.
Static method reference
A reference such as Integer::parseInt, where no object is involved.
Bound reference
A reference to an instance method of a particular object, such as System.out::println.
Unbound reference
A reference such as Part::code, where the first argument becomes the object the method is called on.
Constructor reference
A reference such as Part::new that calls a constructor chosen by the target interface.
Array constructor reference
A reference such as String[]::new that creates an array of a given length.
Comparator.comparing
A static method that builds a Comparator from a function that extracts a sort key.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Rewrite s -> Integer.parseInt(s) as a method reference.

    Show answer

    Integer::parseInt.

  2. Which interface does Part::code fit?

    Show answer

    Function<Part, String>, because the part becomes the object and code() returns a String.

  3. Why does String::compareToIgnoreCase fit Comparator<String>?

    Show answer

    The first string calls the method with the second string as its argument.

  4. With a Supplier, which constructor does ArrayList::new use?

    Show answer

    The no-argument constructor.

  5. Should p -> p.quantity() * 2 become a method reference?

    Show answer

    No; it does more than call one method, so the lambda is clearer.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz