Lambda or method reference?
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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); }}Order[id=O-7, customer=Asha, amount=1450] Order[id=O-4, customer=Meera, amount=1200] [#7, #4]
What this code does
Order::customerandSystem.out::printlnreplaced 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 andc -> ("#" + c).toLowerCase()has two steps. Both stay lambdas.o -> !isBigOrder(o)stays a lambda too, thoughPredicate.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.
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 againWhen 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.
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
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); }}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 inmain. - With
Integer::parseIntthat frame is gone; the trace goes fromparseAllstraight intoInteger.parseInt. When you seelambda$...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).
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.
- Writing brackets:
System.out::println()orforEach(System.out.println). A reference names the method; it never calls it. - Choosing the wrong kind:
String::lengthwhere aSupplieris needed, orstr::lengthwhere aFunctionis needed. - Ambiguous overloads:
Integer::toStringas aFunction<Integer, String>. - Wrong argument order: with
String::contains, the first input is the object, sotest("nan", "banana")asks the opposite question. - 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
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); }}BracketMistakeDemo.java:6: error: cannot find symbol
toppers.forEach(System.out.println);
^
symbol: variable println
location: variable out of type PrintStream
1 errorWhat this code does
- Without
::, Java readsSystem.out.printlnas a field namedprintlnonSystem.out, which does not exist. WritingSystem.out::println()instead gives a syntax error, because a reference never has brackets. - Fix:
toppers.forEach(System.out::println);names the method, ortoppers.forEach(t -> System.out.println(t));calls it inside a lambda.
Example 4 · Mistake: wrong argument order compiles and lies
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); } }}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 areString. - 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 3Interview 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