Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Modern Java

    Method References

    Instead of writing a note that says "call the name method on whatever you're given", you just write the name of the method: "use name".

    Chapter 3 of 112 min read

    The Plain Picture#

    Instead of writing a note that says "call the name method on whatever you're given", you just write the name of the method: "use name".

    The Real Name#

    A method reference is shorthand for a lambda that only calls one existing method. Four kinds:

    KindSyntaxSame as the lambda
    static methodInteger::parseInts -> Integer.parseInt(s)
    instance method of a particular objectSystem.out::printlnx -> System.out.println(x)
    instance method of any object of a typeStudent::name, String::trims -> s.name(), s -> s.trim()
    constructorArrayList::new() -> new ArrayList<>()
    Java
    students.stream().map(Student::name)                              // each student → its name
    list.forEach(System.out::println)                                 // print each
    count.merge(word, 1, Integer::sum)                                // (a, b) -> a + b  (07_java_collections_internals.md Ch 4)
    Comparator.comparingInt(Student::score)                           // (07 Ch 7)

    Use a method reference when it's clearer; use a lambda when the logic is more than one call. s -> s.score() >= 150 has no method-reference form.

    Check yourself

    2 questions
    1

    Write the lambda equivalent of String::length and HashMap::new.

    Show answer

    s -> s.length(); () -> new HashMap<>().

    2

    What does Student::name mean inside map(...)?

    Show answer

    "For each student, call its name() method" — a function from Student to String.