Skip to lesson

Lambda or method reference?

A lambda and a method reference produce the same kind of object, so choosing between them is a readability decision. A reference wins when the method name says everything; a lambda wins when there is any extra logic.

Use a reference when the method name says it all

A method reference and a lambda compile to the same kind of object, so the choice is about readability. Use a reference when the method name already tells the whole story.

Example 1 · Refactor: references where they fit, lambdas where they do not

RefactorDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record Order(String id, String customer, int amount) {}
public class RefactorDemo {    static boolean isBigOrder(Order o) {        return o.amount() >= 1000 && !o.customer().isBlank();    }
    public static void main(String[] args) {        List<Order> orders = new ArrayList<>(List.of(                new Order("O-7", "Asha", 1450),                new Order("O-3", "", 2200),                new Order("O-9", "Ravi", 640),                new Order("O-4", "Meera", 1200)));
        List<Order> big = new ArrayList<>(orders);        // a condition with "not": stays a lambda        big.removeIf(o -> !isBigOrder(o));        // one call each: references        big.sort(Comparator.comparing(Order::customer));        big.forEach(System.out::println);
        // lambdas: extra argument and two steps        List<String> codes = new ArrayList<>();        for (Order o : big) {            codes.add(o.id());        }        codes.replaceAll(c -> c.substring(2));        codes.replaceAll(c -> ("#" + c).toLowerCase());        System.out.println(codes);    }}
Output
Order[id=O-7, customer=Asha, amount=1450]
Order[id=O-4, customer=Meera, amount=1200]
[#7, #4]

What this code does

  • Order::customer and System.out::println replaced lambdas that only passed their input along. The rule for a "big order" lives in a named method, isBigOrder, so the reader sees a name instead of a long condition.
  • c -> c.substring(2) has a fixed argument and c -> ("#" + c).toLowerCase() has two steps. Both stay lambdas. o -> !isBigOrder(o) stays a lambda too, though Predicate.not(RefactorDemo::isBigOrder) would also work.

names.removeIf(String::isBlank) reads as "remove if blank". list.sort(Comparator.comparingInt(Student::marks)) reads as "sort by marks". The lambda versions add s -> s. and nothing else.

A reference is not always better. this::process or Helper::apply hide what happens behind a vague name, while order -> order.total() > 500 shows the rule at once. A rule of thumb:

  • Body is one call that passes the parameters straight through → a reference is usually clearer.
  • The method name describes the action (isBlank, trim, marks) → reference.
  • The name is vague or the class name is very long → a lambda with a good parameter name may read better.
  • Either way, be consistent inside one chain or one class.

When a lambda is clearer

Some lambdas cannot become references at all, and others only through an awkward helper. Keep a lambda when the body has an extra argument, two steps, a condition, swapped order or an ignored input.

Java
Function<String, String> code = s -> s.substring(0, 3);        // extra argumentFunction<String, String> clean = s -> s.trim().toUpperCase();  // two stepsPredicate<Integer> pass = m -> m >= 40;                        // a conditionComparator<String> zToA = (a, b) -> b.compareTo(a);            // swapped orderFunction<String, List<String>> fresh = k -> new ArrayList<>(); // ignored input
static boolean isEligible(Applicant a) {                       // a longer rule gets a name...    return a.marks() >= 60 && a.age() <= 25;}Predicate<Applicant> eligible = Rules::isEligible;             // ...and is a reference again

When such a lambda grows past one line, or is used in several places, move it into a named method: static boolean isEligible(Applicant a). Then Rules::isEligible is a reference again, and the name explains the rule.

The five signs, one each: s -> s.substring(0, 3) has an extra argument, s -> s.trim().toUpperCase() has two steps, m -> m >= 40 has a condition, (a, b) -> b.compareTo(a) has swapped order, and k -> new ArrayList<>() ignores its input.

Do not force a reference by inventing a tiny helper used once. m -> m >= 40 is already as clear as code can be.

Reading stack traces and errors

Synthetic method is a method the compiler writes for you. Every lambda body is moved into one, with a name such as lambda$main$0, which is why that name shows up in stack traces.

When code inside a lambda throws, the stack trace shows a frame such as lambda$main$0, because the compiler moves each lambda body into a hidden method it writes for you. A method reference has no such frame.

Example 2 · The same failure in a lambda and in a method reference

TraceDemo.javaJava
import java.util.List;import java.util.function.Function;
public class TraceDemo {    static void parseAll(List<String> input, Function<String, Integer> parser) {        try {            for (String s : input) {                parser.apply(s);            }        } catch (NumberFormatException e) {            System.out.println(e.getMessage());            for (StackTraceElement frame : e.getStackTrace()) {                if (frame.getClassName().equals("TraceDemo")) {                    System.out.println("  at TraceDemo." + frame.getMethodName());                }            }        }    }
    public static void main(String[] args) {        List<String> marks = List.of("85", "ninety");        System.out.println("Lambda:");        parseAll(marks, s -> Integer.parseInt(s));        System.out.println("Method reference:");        parseAll(marks, Integer::parseInt);    }}
Output
Lambda:
For input string: "ninety"
  at TraceDemo.lambda$main$0
  at TraceDemo.parseAll
  at TraceDemo.main
Method reference:
For input string: "ninety"
  at TraceDemo.parseAll
  at TraceDemo.main

What this code does

  • Only the frames from our own class are printed. With the lambda, the trace has an extra frame lambda$main$0: the hidden method that holds the lambda body, the first lambda written in main.
  • With Integer::parseInt that frame is gone; the trace goes from parseAll straight into Integer.parseInt. When you see lambda$... in a real trace, find the lambda by its method name and number.

The hidden method is called a synthetic method, named after the method that contains it and a counter. With a method reference the trace goes straight from your code into the real method, such as Integer.parseInt.

Compile errors about references usually say "invalid method reference" and then give the real reason on the next lines. Read those lines: "cannot find symbol" (wrong name), "unexpected instance method found in unbound lookup" (an object is missing), "reference to X is ambiguous" (overloads), or "actual and formal argument lists differ in length" (wrong number of inputs).

If a trace says lambda$process$2, look for the third lambda written inside the method process.

The common mistakes

Most method reference bugs come from a small set of mistakes. The first three do not compile; the last two compile and give wrong results, which makes them more dangerous.

  1. Writing brackets: System.out::println() or forEach(System.out.println). A reference names the method; it never calls it.
  2. Choosing the wrong kind: String::length where a Supplier is needed, or str::length where a Function is needed.
  3. Ambiguous overloads: Integer::toString as a Function<Integer, String>.
  4. Wrong argument order: with String::contains, the first input is the object, so test("nan", "banana") asks the opposite question.
  5. A constructor that silently gets the key: computeIfAbsent(year, ArrayList::new) uses the year as the list capacity.

Example 3 · Mistake: calling the method instead of naming it

BracketMistakeDemo.javaJava
import java.util.List;
public class BracketMistakeDemo {    public static void main(String[] args) {        List<String> toppers = List.of("Asha", "Divya", "Ravi");        toppers.forEach(System.out.println);    }}
Sample compiler output
BracketMistakeDemo.java:6: error: cannot find symbol
        toppers.forEach(System.out.println);
                                  ^
  symbol:   variable println
  location: variable out of type PrintStream
1 error

What this code does

  • Without ::, Java reads System.out.println as a field named println on System.out, which does not exist. Writing System.out::println() instead gives a syntax error, because a reference never has brackets.
  • Fix: toppers.forEach(System.out::println); names the method, or toppers.forEach(t -> System.out.println(t)); calls it inside a lambda.

Example 4 · Mistake: wrong argument order compiles and lies

OrderBugDemo.javaJava
import java.util.List;import java.util.function.BiPredicate;
public class OrderBugDemo {    public static void main(String[] args) {        List<String> messages = List.of("Your OTP is 4821", "Fee paid", "OTP expired");        BiPredicate<String, String> contains = String::contains;   // (a, b) -> a.contains(b)
        System.out.println("Buggy: word first");        for (String m : messages) {            System.out.println("  " + contains.test("OTP", m) + " : " + m);        }
        System.out.println("Fixed: message first");        for (String m : messages) {            System.out.println("  " + contains.test(m, "OTP") + " : " + m);        }    }}
Output
Buggy: word first
  false : Your OTP is 4821
  false : Fee paid
  false : OTP expired
Fixed: message first
  true : Your OTP is 4821
  false : Fee paid
  true : OTP expired

What this code does

  • For an unbound reference the first input is the object. contains.test("OTP", m) asks whether "OTP" contains the whole message, which is false every time. The compiler cannot catch it, because both inputs are String.
  • Passing the message first fixes it. When the order is easy to confuse, a lambda with clear names, (message, word) -> message.contains(word), documents the roles better than the reference.

Find the bug

Find the reference mistake

Tap the line that is wrong, then check the fix.

Sort the names by length.

Round 1 of 3

Interview point: are method references faster than lambdas?

No meaningful difference. Both are compiled to an invokedynamic instruction, and the JVM builds the functional-interface object the first time that line runs. A lambda body becomes a private synthetic method; a reference usually points straight at the target method. After the JIT compiler, the part of the JVM that turns hot code into machine code, has optimised them, both cost the same.

The real differences are about behaviour, not speed. A bound reference evaluates its receiver at once and fails early on null; a lambda reads variables only when it runs. So the honest interview answer is: choose for readability and correct timing, not for speed.

Next step

Check your understanding

12 quick questions