Skip to lesson

Method references: practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Every method reference is a one-call lambda written shorter, and each one is static, bound, unbound or a constructor. Practice comes down to two skills: picking the right kind fast, and seeing when a lambda is the better choice.

Pick the kind in four questions

Converting a lambda to a method reference is a short checklist. First ask whether a reference is possible at all: the body must be one call that passes the lambda's parameters straight through, in the same order. If not, stop: it stays a lambda.

  1. A class name in front of a static method, as in s -> Integer.parseInt(s) → static: Integer::parseInt.
  2. An object that exists before the call, as in s -> log.add(s) → bound: log::add.
  3. The first parameter itself, as in s -> s.trim() or (a, b) -> a.compareTo(b) → unbound: String::trim, String::compareTo.
  4. The word new, as in n -> new Ticket(n) or n -> new int[n] → constructor: Ticket::new, int[]::new.

Example 1 · Converting a batch of lambdas to all four kinds

ConvertBatchDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.BiFunction;import java.util.function.Consumer;import java.util.function.Function;import java.util.function.IntFunction;import java.util.function.Predicate;import java.util.function.Supplier;
record Ticket(String pnr, int seats) {}
public class ConvertBatchDemo {    public static void main(String[] args) {        List<String> log = new ArrayList<>();
        // before: s -> Integer.parseInt(s)          after: static        Function<String, Integer> parse = Integer::parseInt;        // before: s -> log.add(s)                   after: bound        Consumer<String> remember = log::add;        // before: s -> s.isBlank()                  after: unbound        Predicate<String> blank = String::isBlank;        BiFunction<String, Integer, Ticket> book = Ticket::new;        Supplier<List<Ticket>> newCart = ArrayList::new;        IntFunction<String[]> newArray = String[]::new;
        List<Ticket> cart = newCart.get();        for (String line : List.of("PNR1:2", " ", "PNR2:4")) {            if (blank.test(line)) {                remember.accept("skipped blank line");                continue;            }            String[] p = line.split(":");            cart.add(book.apply(p[0], parse.apply(p[1])));        }        cart.forEach(System.out::println);        System.out.println(log);        System.out.println(newArray.apply(3).length);    }}
Output
Ticket[pnr=PNR1, seats=2]
Ticket[pnr=PNR2, seats=4]
[skipped blank line]
3

What this code does

  • The first three comments show the lambda and its kind. The kind follows from what stood in front of the method: a class with a static method, an existing object, the parameter itself, or new.
  • line.split(":") stays a call inside the loop: it has a fixed argument, so it would need a lambda. Not everything should be a reference.
  • The three constructor references replace (p, n) -> new Ticket(p, n), () -> new ArrayList<>() and n -> new String[n]; the last one is an array constructor reference.

If it is possible, the call itself tells you the kind. Look at what sits in front of the method name inside the lambda.

Sort a contact list with chained references

A phone contact list is a good test of comparator chains. Favourites come first, then contacts are grouped by city, then sorted by name without caring about case.

Example 2 · Sorting contacts: favourites, city, then name

ContactSortDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record Contact(String name, String city, boolean favourite) {}
public class ContactSortDemo {    public static void main(String[] args) {        List<Contact> contacts = new ArrayList<>(List.of(                new Contact("ravi", "Pune", false),                new Contact("Asha", "Delhi", true),                new Contact("meera", "Delhi", false),                new Contact("Bala", "Pune", true),                new Contact("arjun", "Delhi", false)));
        Comparator<Contact> order = Comparator.comparing(Contact::favourite).reversed()                .thenComparing(Contact::city)                .thenComparing(Contact::name, String::compareToIgnoreCase);
        contacts.sort(order);        for (Contact c : contacts) {            System.out.println((c.favourite() ? "* " : "  ") + c.city() + " " + c.name());        }    }}
Output
* Delhi Asha
* Pune Bala
  Delhi arjun
  Delhi meera
  Pune ravi

What this code does

  • Boolean sorts false before true, so reversed() right after the favourite key puts favourites first. It flips only that key, because it comes before the other thenComparing calls.
  • thenComparing(Contact::name, String::compareToIgnoreCase) uses an unbound accessor as the key and an unbound two-input reference as the comparator for it, so arjun comes before meera.

Each rule is one key: Comparator.comparing(Contact::favourite).reversed() (because false sorts before true), then .thenComparing(Contact::city), then .thenComparing(Contact::name, String::compareToIgnoreCase). The last form takes a key and a comparator for that key. Keep reversed() right after the key it should flip. At the end of the chain it would reverse every key, not just the first.

Text to objects, and the lambdas that stay

Text input, such as a file of lines like Asha;CSE;91, goes through three steps: split, parse, build. Splitting needs a fixed argument, so it stays a lambda: line -> line.split(";").

Example 3 · Building objects from text with constructor references

FromLinesDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.function.BiFunction;import java.util.function.Function;
record Student(String name, int marks) {}
public class FromLinesDemo {    static <T> List<T> parse(List<String> lines, Function<String[], T> builder) {        List<T> out = new ArrayList<>();        for (String line : lines) {            if (line.isBlank()) {                continue;            }            out.add(builder.apply(line.split(";")));        }        return out;    }
    public static void main(String[] args) {        List<String> lines = List.of("Asha;91", "Ravi;78", "", "Meera;85");
        BiFunction<String, Integer, Student> make = Student::new;        Function<String, Integer> toInt = Integer::parseInt;
        // turning the parts into a Student needs two steps, so this one stays a lambda        List<Student> students = parse(lines, p -> make.apply(p[0].strip(), toInt.apply(p[1].strip())));
        Student[] array = students.toArray(Student[]::new);        System.out.println(array.length + " students");        System.out.println(Arrays.toString(array));    }}
Output
3 students
[Student[name=Asha, marks=91], Student[name=Ravi, marks=78], Student[name=Meera, marks=85]]

What this code does

  • Student::new and Integer::parseInt do the building and parsing. The glue that picks p[0] and p[1] and strips them has fixed indexes and several calls, so it is honestly a lambda.
  • toArray(Student[]::new) returns a real Student[]. The blank line is skipped inside parse before any object is built.

Parsing uses static references like Integer::parseInt. Building uses a constructor reference like Student::new, and toArray(Student[]::new) gives a typed array at the end.

The lambdas that should stay lambdas are easy to spot once you know the signs: a condition, a fixed argument, two calls, swapped order, an ignored input, or a null check. Forcing any of these into a reference either fails to compile or needs a helper that makes the code longer.

A good final check: read the line aloud. removeIf(String::isBlank) reads as English; removeIf(Checks::check1) does not, so rename the method or use a lambda.

Finish up

Mark complete & continue

Next: What is a stream?