SyntaxPilot
Courses/Java/Lesson 36
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Java · Lesson 36 of 51

Lambdas and method references

queued

These are the notes for Java episode 36. Ravi's menu app needs answers to many questions ("what's under Rs 20?", "which ones are chai?"), and each question becomes a copy-pasted method that differs in one condition. We pass the condition in as an object (an interface plus a class, then an anonymous class), notice the ceremony, and invent the lambda expression: behaviour passed as a value. Then we learn the rules: a lambda needs a target type, which must be a functional interface; Java's ready-made ones in java.util.function; the effectively final rule; lambdas in collection methods; and method references. Every example was run with javac 21.

The problem: copy-pasted methods

import java.util.ArrayList;
import java.util.List;

record Item(String name, int price) {}

public class Main {
    static List<Item> cheap(List<Item> menu) {
        List<Item> out = new ArrayList<>();
        for (Item i : menu) if (i.price() < 20) out.add(i);
        return out;
    }
    static List<Item> chai(List<Item> menu) {
        List<Item> out = new ArrayList<>();
        for (Item i : menu) if (i.name().contains("chai")) out.add(i);
        return out;
    }
    public static void main(String[] args) {
        List<Item> menu = List.of(
                new Item("masala chai", 15), new Item("samosa", 12),
                new Item("cold coffee", 60), new Item("ginger chai", 25));
        System.out.println(cheap(menu));
        System.out.println(chai(menu));
    }
}
[Item[name=masala chai, price=15], Item[name=samosa, price=12]]
[Item[name=masala chai, price=15], Item[name=ginger chai, price=25]]

Both methods are the same loop with a different if. Fifty questions would mean fifty copies, and a bug fixed in one must be fixed in all. Only the test changes, so the test should be a parameter.

Passing a rule as an object

import java.util.ArrayList;
import java.util.List;

record Item(String name, int price) {}

interface Check {
    boolean test(Item i);
}

class Cheap implements Check {
    public boolean test(Item i) { return i.price() < 20; }
}

public class Main {
    static List<Item> filter(List<Item> menu, Check rule) {
        List<Item> out = new ArrayList<>();
        for (Item i : menu) if (rule.test(i)) out.add(i);
        return out;
    }
    public static void main(String[] args) {
        List<Item> menu = List.of(
                new Item("masala chai", 15), new Item("samosa", 12),
                new Item("cold coffee", 60), new Item("ginger chai", 25));
        System.out.println(filter(menu, new Cheap()));
        System.out.println(filter(menu, new Check() {
            public boolean test(Item i) { return i.name().contains("chai"); }
        }));
    }
}
[Item[name=masala chai, price=15], Item[name=samosa, price=12]]
[Item[name=masala chai, price=15], Item[name=ginger chai, price=25]]

One filter loop now serves every question. But each rule costs a class (Cheap) or an anonymous class (episode 23): a header, public, boolean, return, braces: five lines of ceremony around one idea, i.price() < 20. (Episode 34's ByName comparator had the same problem.)

Lambdas

Real-life example: a hired helper vs a sticky note.

At the stall In Java Meaning
Hire a helper: name, contract, one job a class Cheap implements Check heavy
A sticky note: "price under 20" the lambda i -> i.price() < 20 just the rule
The checker knows the note is a test for one item the target interface Check.test(Item) the context gives the meaning

A lambda expression is an anonymous function written as parameters -> body. It creates an object that implements a functional interface, without writing a class.

import java.util.ArrayList;
import java.util.List;

record Item(String name, int price) {}

interface Check {
    boolean test(Item i);
}

public class Main {
    static List<Item> filter(List<Item> menu, Check rule) {
        List<Item> out = new ArrayList<>();
        for (Item i : menu) if (rule.test(i)) out.add(i);
        return out;
    }
    public static void main(String[] args) {
        List<Item> menu = List.of(
                new Item("masala chai", 15), new Item("samosa", 12),
                new Item("cold coffee", 60), new Item("ginger chai", 25));
        System.out.println(filter(menu, i -> i.price() < 20));
        System.out.println(filter(menu, i -> i.name().contains("chai")));
        System.out.println(filter(menu, i -> i.price() > 50));
        Check premium = (Item i) -> {
            boolean costly = i.price() >= 25;
            return costly && !i.name().contains("samosa");
        };
        System.out.println(filter(menu, premium));
    }
}
[Item[name=masala chai, price=15], Item[name=samosa, price=12]]
[Item[name=masala chai, price=15], Item[name=ginger chai, price=25]]
[Item[name=cold coffee, price=60]]
[Item[name=cold coffee, price=60], Item[name=ginger chai, price=25]]

Lambda syntax, step by step

(Item i) -> { return i.price() < 20; }   // full form
(i) -> { return i.price() < 20; }        // parameter type inferred
i -> { return i.price() < 20; }          // one parameter: brackets optional
i -> i.price() < 20                      // one expression: braces and return go, value is returned
() -> "chai"                             // no parameters
(a, b) -> a + b                          // two parameters

You can write all parameter types or none; you cannot mix: (Integer a, b) -> a + b gives error: invalid lambda parameter declaration (cannot mix implicitly-typed and explicitly-typed parameters).

Functional interfaces: the target type

public class Main {
    public static void main(String[] args) {
        var twice = x -> x * 2;
        System.out.println(twice);
    }
}
Main.java:3: error: cannot infer type for local variable twice
        var twice = x -> x * 2;
            ^
  (lambda expression needs an explicit target-type)
1 error

On its own a lambda has no type: Java doesn't know what x is or which method the lambda implements. It needs a target type: the type of the variable, parameter or return value it is assigned to. That type must be a functional interface: an interface with exactly one abstract method (default and static methods don't count).

@FunctionalInterface
interface Check {
    boolean test(int price);
    boolean testAgain(int price);
}

public class Main {
    public static void main(String[] args) {
        Check cheap = p -> p < 20;
        System.out.println(cheap.test(15));
    }
}
Main.java:1: error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
  Check is not a functional interface
    multiple non-overriding abstract methods found in interface Check
Main.java:9: error: incompatible types: Check is not a functional interface
        Check cheap = p -> p < 20;
                      ^
    multiple non-overriding abstract methods found in interface Check
2 errors

@FunctionalInterface is optional, but asks the compiler to check that the interface has exactly one abstract method. Interfaces you already know are functional: Comparator<T> (compare), Runnable (run), Comparable<T> (compareTo).

Ready-made functional interfaces (java.util.function)

Interface Method Shape Example
Predicate<T> boolean test(T t) T → boolean p -> p < 20
Function<T, R> R apply(T t) T → R p -> p + p * 5 / 100
Consumer<T> void accept(T t) T → nothing s -> System.out.println(s)
Supplier<T> T get() nothing → T () -> "kulhad chai"
BinaryOperator<T> T apply(T a, T b) (T, T) → T (a, b) -> a + b
UnaryOperator<T> T apply(T t) T → T s -> s.toUpperCase()
BiFunction<T, U, R> R apply(T t, U u) (T, U) → R (name, qty) -> name + " x" + qty

There are also primitive versions such as IntPredicate, IntFunction<R>, ToIntFunction<T> that avoid boxing.

import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        Predicate<Integer> cheap = p -> p < 20;
        Function<Integer, Integer> withGst = p -> p + p * 5 / 100;
        Consumer<String> shout = s -> System.out.println(s.toUpperCase() + "!");
        Supplier<String> special = () -> "Today's special: kulhad chai";
        BinaryOperator<Integer> add = (a, b) -> a + b;

        System.out.println(cheap.test(15) + " " + cheap.test(60));
        System.out.println(withGst.apply(200));
        shout.accept("chai ready");
        System.out.println(special.get());
        System.out.println(add.apply(15, 12));
        System.out.println(cheap.and(p -> p > 10).test(5));
    }
}
true false
210
CHAI READY!
Today's special: kulhad chai
27
false

You call a lambda through its interface's method: cheap.test(15), not cheap(15). Predicates combine with and, or and negate; Functions with andThen and compose.

Effectively final: what a lambda can use

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> prices = List.of(15, 12, 60);
        int discount = 5;
        prices.forEach(p -> System.out.println(p - discount));
        discount = 10;
    }
}
Main.java:7: error: local variables referenced from a lambda expression must be final or effectively final
        prices.forEach(p -> System.out.println(p - discount));
                                                   ^
1 error

A lambda can use (capture) local variables from the surrounding method, but only if they are final or effectively final: never assigned again after their first value. The lambda may run later (even after the method returns), so it keeps a copy; a variable that could still change would make that copy ambiguous. Fields (this.x, static variables) are not restricted this way. Deleting discount = 10; makes the program compile.

Lambdas in collection methods

import java.util.ArrayList;
import java.util.List;

record Item(String name, int price) {}

public class Main {
    public static void main(String[] args) {
        List<Item> menu = new ArrayList<>(List.of(
                new Item("masala chai", 15), new Item("samosa", 12),
                new Item("cold coffee", 60), new Item("ginger chai", 25)));

        menu.removeIf(i -> i.price() > 50);
        menu.sort((a, b) -> a.name().compareTo(b.name()));
        menu.forEach(i -> System.out.println(i.name() + " Rs " + i.price()));

        List<String> names = new ArrayList<>(List.of("chai", "samosa", "vada pav"));
        names.replaceAll(s -> s.toUpperCase());
        System.out.println(names);
    }
}
ginger chai Rs 25
masala chai Rs 15
samosa Rs 12
[CHAI, SAMOSA, VADA PAV]
Method Takes Does
list.removeIf(pred) Predicate<T> removes every element where the test is true
list.sort(cmp) Comparator<T> sorts in place
list.forEach(action) Consumer<T> runs the action on each element
list.replaceAll(op) UnaryOperator<T> replaces each element with op's result
map.forEach((k, v) -> ...) BiConsumer<K, V> visits each key-value pair
map.computeIfAbsent(k, f) Function<K, V> creates a missing value

Method references

Real-life example: pointing at the recipe page. Writing s -> s.toUpperCase() is like copying out a recipe that is already printed in the cookbook. Pointing at the page, String::toUpperCase, says the same thing. A method reference (::) is a shorter lambda that only calls one existing method.

Kind Syntax Same as
Static method Integer::parseInt s -> Integer.parseInt(s)
Instance method of any object of a type String::toUpperCase s -> s.toUpperCase()
Instance method of a particular object System.out::println x -> System.out.println(x)
Constructor ArrayList::new () -> new ArrayList<>()
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;

record Item(String name, int price) {}

public class Main {
    public static void main(String[] args) {
        Function<String, Integer> parse = Integer::parseInt;   // static
        System.out.println(parse.apply("15") + 1);

        List<String> names = new ArrayList<>(List.of("chai", "samosa"));
        names.replaceAll(String::toUpperCase);   // any String
        names.forEach(System.out::println);      // one object

        Supplier<List<Item>> newTray = ArrayList::new;   // constructor
        List<Item> tray = newTray.get();
        tray.add(new Item("chai", 15));
        System.out.println(tray);
    }
}
16
CHAI
SAMOSA
[Item[name=chai, price=15]]

Episode 34's comparators, revisited:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

record Item(String name, int price) {}

public class Main {
    public static void main(String[] args) {
        List<Item> menu = new ArrayList<>(List.of(new Item("samosa", 12),
                new Item("masala chai", 15), new Item("ginger chai", 25)));

        menu.sort((a, b) -> Integer.compare(a.price(), b.price()));
        System.out.println(menu.get(0).name());

        menu.sort(Comparator.comparing(Item::name));
        System.out.println(menu.get(0).name());

        menu.sort(Comparator.comparing(i -> i.name().length()));
        System.out.println(menu.get(0).name());
    }
}
samosa
ginger chai
samosa

Comparator.comparing takes a Function (the key extractor) and builds a comparator; Item::name is that function.

Before and after

// before: anonymous class
menu.sort(new Comparator<Item>() {
    public int compare(Item a, Item b) {
        return a.name().compareTo(b.name());
    }
});

// after: lambda, or method reference
menu.sort((a, b) -> a.name().compareTo(b.name()));
menu.sort(Comparator.comparing(Item::name));

A lambda is not magic: it is a compact way to create an object that implements a functional interface. Unlike an anonymous class, this inside a lambda means the enclosing object, and a lambda cannot declare a variable with the same name as a local variable around it.

Common mistakes (and the real error messages)

Mistake What you see Why Fix
var twice = x -> x * 2; error: cannot infer type for local variable twice (lambda expression needs an explicit target-type) no target type Function<Integer, Integer> twice = x -> x * 2;
@FunctionalInterface with two abstract methods error: Unexpected @FunctionalInterface annotation ... multiple non-overriding abstract methods found in interface Check which method is the lambda? exactly one abstract method
Assigning a lambda to that interface error: incompatible types: Check is not a functional interface same same
Changing a captured local error: local variables referenced from a lambda expression must be final or effectively final the lambda keeps a copy don't reassign; copy to a new variable
cheap(15) on a Predicate error: cannot find symbol symbol: method cheap(int) a lambda is an object cheap.test(15)

Mini project: a menu board with pluggable rules

One show method takes three behaviours as parameters: what to keep, how to order, and how to label each item.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

record Item(String name, String type, int price) {}

public class Main {
    static void show(String title, List<Item> menu, Predicate<Item> keep,
                     Comparator<Item> order, Function<Item, String> label) {
        List<Item> picked = new ArrayList<>(menu);
        picked.removeIf(keep.negate());
        picked.sort(order);
        System.out.println(title);
        picked.forEach(i -> System.out.println("  " + label.apply(i)));
    }

    public static void main(String[] args) {
        List<Item> menu = List.of(
                new Item("masala chai", "drink", 15), new Item("samosa", "snack", 12),
                new Item("cold coffee", "drink", 60), new Item("ginger chai", "drink", 25),
                new Item("vada pav", "snack", 20), new Item("poha", "snack", 30));

        show("Under Rs 25, cheapest first:", menu, i -> i.price() < 25,
                Comparator.comparingInt(Item::price), i -> i.name() + " Rs " + i.price());
        show("Drinks A-Z:", menu, i -> i.type().equals("drink"),
                Comparator.comparing(Item::name), Item::name);
        Predicate<Item> snack = i -> i.type().equals("snack");
        show("Snacks, priciest first:", menu, snack.and(i -> i.price() >= 20),
                Comparator.comparingInt(Item::price).reversed(), i -> i.name().toUpperCase());
    }
}
Under Rs 25, cheapest first:
  samosa Rs 12
  masala chai Rs 15
  vada pav Rs 20
Drinks A-Z:
  cold coffee
  ginger chai
  masala chai
Snacks, priciest first:
  POHA
  VADA PAV

keep.negate() flips the predicate so removeIf removes what we don't want to keep.

Practice

  1. Keep only the words longer than 4 letters, using a Predicate and removeIf.
  2. A Function<Integer, String> that turns marks into grades (A ≥ 90, B ≥ 75, C ≥ 50, else F).
  3. Sort employees by salary, highest first, with a lambda.
  4. Rewrite three lambdas as method references.
Solution 1
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>(List.of("chai", "samosa", "jalebi", "poha", "dosa", "biryani"));
        Predicate<String> isLong = w -> w.length() > 4;
        words.removeIf(isLong.negate());
        System.out.println(words);
    }
}
[samosa, jalebi, biryani]
Solution 2
import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<Integer, String> grade = m -> m >= 90 ? "A" : m >= 75 ? "B" : m >= 50 ? "C" : "F";
        for (int m : new int[]{95, 80, 62, 40}) System.out.println(m + " -> " + grade.apply(m));
    }
}
95 -> A
80 -> B
62 -> C
40 -> F
Solution 3
import java.util.ArrayList;
import java.util.List;

record Employee(String name, int salary) {}

public class Main {
    public static void main(String[] args) {
        List<Employee> staff = new ArrayList<>(List.of(new Employee("Ravi", 52000),
                new Employee("Asha", 71000), new Employee("Kabir", 48000)));
        staff.sort((a, b) -> Integer.compare(b.salary(), a.salary()));   // highest first
        staff.forEach(e -> System.out.println(e.name() + " " + e.salary()));
    }
}
Asha 71000
Ravi 52000
Kabir 48000

Swapping b and a in Integer.compare sorts in descending order; Comparator.comparingInt(Employee::salary).reversed() does the same.

Solution 4
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("asha", "ravi"));
        names.replaceAll(String::toUpperCase);          // was: s -> s.toUpperCase()
        names.forEach(System.out::println);             // was: s -> System.out.println(s)
        Function<String, Integer> len = String::length; // was: s -> s.length()
        System.out.println(len.apply("samosa"));
    }
}
ASHA
RAVI
6

Quick quiz

Function<Integer, Integer> gst = p -> p + p / 10;
Predicate<Integer> big = p -> p > 100;
int price = 95;
System.out.println(big.test(gst.apply(price)));

A) true B) false C) 104 D) Compile error: price is not final

Answer

A. gst.apply(95) = 95 + 95 / 10 = 95 + 9 = 104 (integer division). big.test(104) is true. price is never reassigned, so it is effectively final anyway.

true

Interview questions

  1. What is a lambda expression? An anonymous function, params -> body, that provides the implementation of a functional interface's single abstract method.
  2. What is a functional interface? An interface with exactly one abstract method, e.g. Runnable, Comparator, Predicate. @FunctionalInterface makes the compiler verify it.
  3. Can a functional interface have default or static methods? Yes, any number; only abstract methods are counted. Abstract methods that override Object's public methods (like equals) don't count either.
  4. What does "effectively final" mean? A local variable that is never reassigned after initialisation. Only such variables can be captured by lambdas (and anonymous/local classes).
  5. Lambda vs anonymous class? A lambda is shorter, works only for functional interfaces, has no state of its own, and this refers to the enclosing instance. An anonymous class can implement interfaces with several methods, extend classes, and hold fields.
  6. Name the four kinds of method reference. Static (Integer::parseInt), instance method of an arbitrary object (String::length), instance method of a particular object (System.out::println), constructor (ArrayList::new).
  7. Predicate vs Function vs Consumer vs Supplier? T→boolean, T→R, T→void, ()→T.
  8. Is Comparator a functional interface even though it has many methods? Yes: only compare is abstract (equals is from Object); the rest are default or static.

Glossary

Term Meaning Example
Behaviour as a value Passing code (a rule) to a method like data filter(menu, rule)
Anonymous class A class with no name, written where it is used new Check() { ... }
Lambda expression A short anonymous function: params -> body i -> i.price() < 20
Arrow -> Separates the parameters from the body x -> x * 2
Expression body A single expression whose value is returned a + b
Block body Statements in braces with return { return a + b; }
Type inference The compiler works out types you leave out i is an Item
Target type The interface type a lambda is assigned to Check rule = ...
Functional interface Interface with exactly one abstract method Predicate<T>
@FunctionalInterface Annotation that makes the compiler check it on Check
Abstract method A method with no body, to be implemented boolean test(Item i);
java.util.function Package of ready-made functional interfaces Function, Supplier
Predicate T → boolean, method test p -> p < 20
Function T → R, method apply p -> p * 2
Consumer T → nothing, method accept s -> System.out.println(s)
Supplier nothing → T, method get () -> "chai"
BinaryOperator (T, T) → T, method apply (a, b) -> a + b
UnaryOperator T → T s -> s.toUpperCase()
Capture A lambda using a local variable from outside discount
Effectively final Never reassigned after its first value int discount = 5; (unchanged)
removeIf / forEach / replaceAll Collection methods that take lambdas list.removeIf(i -> ...)
Method reference A lambda that just calls an existing method String::toUpperCase
:: The method reference operator System.out::println
Constructor reference Class::new ArrayList::new
Key extractor A Function that picks the field to compare Item::name in comparing

Summary

  • When only one part of the code changes, pass that part in as behaviour.
  • A lambda params -> body is the shortest way to pass behaviour; types are inferred from the target type.
  • The target must be a functional interface: exactly one abstract method (@FunctionalInterface checks it).
  • java.util.function gives you Predicate, Function, Consumer, Supplier, BinaryOperator and more; call them by their method (test, apply, accept, get).
  • Captured local variables must be effectively final.
  • Collections take lambdas: removeIf, sort, forEach, replaceAll.
  • Method references (Class::method, object::method, Class::new) replace lambdas that only call one method.
  • Next: filter, then map, then add up, in one pipeline: Streams (episode 37).