Java Lambda Basics
What a Lambda Expression Is
A lambda expression is a short block of code that you can pass around like a value — store it in a variable, pass it to a method, return it from a method — and run later. It's often described as an anonymous function: a function with parameters and a body, but no name and no class of its own.
(a, b) -> Integer.compare(a.length(), b.length())
This lambda takes two parameters, a and b, and returns the result of comparing their lengths. On its own it does nothing; it's a piece of behaviour that some other code will call.
Lambdas were added in Java 8 (2014). They made it practical to write code that is customised by passing in behaviour — sort this way, keep items that match this rule, run this action when an event happens — and they're the foundation of the Stream API covered later in this section.
The Problem Lambdas Solve
Before Java 8, passing behaviour meant creating an object of a class that implements an interface, usually an anonymous class. Here's the same sort written both ways:
import java.util.*;
public class Before {
public static void main(String[] args) {
List<String> cities = new ArrayList<>(List.of("Madurai", "Chennai", "Salem", "Coimbatore"));
Collections.sort(cities, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
});
System.out.println("anonymous class: " + cities);
cities.sort((a, b) -> Integer.compare(b.length(), a.length()));
System.out.println("lambda: " + cities);
Runnable task = () -> System.out.println("running in " + Thread.currentThread().getName());
task.run();
new Thread(task, "worker-1").start();
}
}
Output:
anonymous class: [Salem, Madurai, Chennai, Coimbatore]
lambda: [Coimbatore, Madurai, Chennai, Salem]
running in main
running in worker-1
- The anonymous class needs six lines of structure —
new Comparator<String>(),@Override, the method signature, braces — around one line that matters:Integer.compare(a.length(), b.length()). - The lambda is just that line, plus the parameter names. The compiler works out everything else: that a
Comparator<String>is needed, that the method iscompare, thataandbareStrings, and that the result is returned. (This lambda sorts longest first, the reverse of the anonymous class.) Runnable task = () -> ...stores behaviour in a variable. The same code runs once directly in themainthread and once in a new thread — the lambda is a value that can be handed to whoever needs it.
Lambdas Need a Functional Interface
A lambda doesn't have a type of its own. It always becomes an instance of a functional interface — an interface with exactly one abstract method. The lambda provides the implementation of that one method.
| Functional interface | Its single abstract method | Example lambda |
|---|---|---|
Runnable | void run() | () -> System.out.println("hi") |
Comparator<T> | int compare(T a, T b) | (a, b) -> a.length() - b.length() |
Predicate<T> | boolean test(T t) | p -> p.stock() == 0 |
Function<T, R> | R apply(T t) | s -> s.length() |
Consumer<T> | void accept(T t) | s -> System.out.println(s) |
Supplier<T> | T get() | () -> new ArrayList<>() |
The interface that the lambda becomes is determined by the context where it's written — the variable it's assigned to, or the parameter type of the method it's passed to. This is called the target type. The same lambda text can therefore become different types in different places, and a lambda can't appear where there is no target type (var f = x -> x * 2; doesn't compile, because the compiler has nothing to infer the type from).
The Functional Interfaces lesson covers these interfaces in detail, and the Lambda Syntax lesson covers all the forms a lambda can take.
Passing Behaviour as a Parameter
The real power of lambdas is behaviour parameterisation: writing one method whose logic is completed by a lambda supplied by the caller.
import java.util.*;
import java.util.function.Predicate;
public class Behaviour {
record Product(String name, String category, double price, int stock) { }
static List<Product> filter(List<Product> items, Predicate<Product> rule) {
List<Product> result = new ArrayList<>();
for (Product p : items) if (rule.test(p)) result.add(p);
return result;
}
public static void main(String[] args) {
List<Product> catalog = List.of(
new Product("Gel pen", "stationery", 25, 400),
new Product("Laptop bag", "bags", 1899, 3),
new Product("Notebook", "stationery", 60, 0),
new Product("Backpack", "bags", 1299, 18));
System.out.println(names(filter(catalog, p -> p.stock() == 0)));
System.out.println(names(filter(catalog, p -> p.category().equals("bags"))));
System.out.println(names(filter(catalog, p -> p.price() < 100 && p.stock() > 0)));
double budget = 1500;
System.out.println(names(filter(catalog, p -> p.price() <= budget)));
}
static List<String> names(List<Product> ps) { return ps.stream().map(Product::name).toList(); }
}
Output:
[Notebook]
[Laptop bag, Backpack]
[Gel pen]
[Gel pen, Notebook, Backpack]
filteris written once. It loops over the products and keeps those for whichrule.test(p)is true; it doesn't know or care what the rule is.- Each call supplies a different rule: out of stock, in the "bags" category, cheap and available, within budget. Without lambdas you'd either write four nearly identical methods (
filterOutOfStock,filterBags, ...) or four anonymous classes. - Parameter types are inferred. Because
filterexpects aPredicate<Product>, the compiler knowspis aProduct, sop.stock()andp.category()compile. - Lambdas can use local variables: the last rule reads
budgetfrom the surrounding method.
The JDK uses this design everywhere: List.removeIf(Predicate), List.sort(Comparator), Map.computeIfAbsent(key, Function), Iterable.forEach(Consumer), and the whole Stream API.
Capturing Variables: Effectively Final
A lambda can read local variables from the method around it — it captures them. There's one rule: captured local variables must be final or effectively final, meaning they're never assigned again after initialisation.
import java.util.function.*;
public class CapErr {
public static void main(String[] args) {
int total = 0;
Runnable r = () -> total++;
int limit = 10;
limit = 20;
Predicate<Integer> p = x -> x > limit;
}
}
CapErr.java:6: error: local variables referenced from a lambda expression must be final or effectively final
Runnable r = () -> total++;
^
CapErr.java:9: error: local variables referenced from a lambda expression must be final or effectively final
Predicate<Integer> p = x -> x > limit;
^
2 errors
total++tries to modify a captured variable.limitis reassigned before the lambda, so it's no longer effectively final — even though the lambda only reads it.
Why the rule exists: a lambda can run later, and even on a different thread, after the method that created it has returned. Local variables live on the method's stack, which disappears when the method returns, so the lambda receives a copy of the value. If the variable could change afterwards, the lambda's copy and the variable would disagree, and with threads the result would be unpredictable. Requiring effectively final variables makes the copy indistinguishable from the original.
What's allowed:
import java.util.*;
import java.util.function.*;
public class Capture {
public static void main(String[] args) {
int threshold = 50;
Predicate<Integer> passed = mark -> mark >= threshold;
System.out.println(passed.test(72) + " " + passed.test(41));
int[] counter = {0};
Runnable increment = () -> counter[0]++;
increment.run();
increment.run();
System.out.println("counter: " + counter[0]);
List<Supplier<String>> greeters = new ArrayList<>();
for (String name : List.of("Asha", "Ravi")) {
greeters.add(() -> "Hello, " + name);
}
greeters.forEach(g -> System.out.println(g.get()));
}
}
Output:
true false
counter: 2
Hello, Asha
Hello, Ravi
- Reading an effectively final variable (
threshold) is the normal case. - Modifying the contents of an object is allowed:
counteritself never changes — it always refers to the same array — but the array's element does. This workaround is fine for simple single-threaded code; it isn't thread-safe, and in stream code asum()orcount()is the better tool. - The enhanced for loop variable is a new variable on each iteration, so it's effectively final and each lambda captures its own
name. (A classicfor (int i = 0; ...; i++)counter is not, becausei++reassigns it.) - Fields (instance and static variables) aren't subject to this rule — they're accessed through the object, not copied.
this Inside a Lambda
A lambda isn't an object of a new class in the way an anonymous class is. Inside a lambda, this means the same as in the surrounding method:
public class This {
private final String name = "outer object";
void show() {
Runnable lambda = () -> System.out.println("lambda this: " + this.name);
Runnable anon = new Runnable() {
private final String name = "anonymous object";
@Override public void run() { System.out.println("anonymous this: " + this.name); }
};
lambda.run();
anon.run();
}
public static void main(String[] args) {
new This().show();
}
}
Output:
lambda this: outer object
anonymous this: anonymous object
- In the lambda,
thisis theThisobject whoseshow()method created it. - In the anonymous class,
thisis the anonymous class's own instance, which has its own fields.
This makes lambdas easier to reason about: their body reads like code in the enclosing method. Lambdas also can't declare fields or have state of their own; when you need that, an anonymous class or a named class is the right tool.
When to Use Lambdas — and When Not To
Use a lambda when:
- an API expects a functional interface (sorting, filtering, event handlers, callbacks, tasks for executors, stream operations);
- the behaviour is short and its meaning is clear at the point of use.
Prefer a named method or class when:
- the logic is longer than a few lines or needs a name to be understood — write a method and refer to it with a method reference (
this::isEligible, see the Method References lesson); - the same logic is used in many places;
- the implementation needs its own fields, multiple methods, or must implement an interface with several abstract methods;
- the behaviour needs to be tested in isolation.
Lambdas that span many lines inside a method call quickly become hard to read and hard to debug (stack traces show synthetic names like lambda$main$0).
Practical Example: Order Event Notifications
When an order is placed, several independent things should happen: an email confirmation, an SMS for express orders, an alert to the sales team for large orders. Registering each reaction as a lambda keeps the order-placing code unaware of what the reactions are, and new reactions can be added without changing it.
import java.util.*;
import java.util.function.*;
public class Notify {
record Order(String id, String customer, String phone, String email, double amount, boolean express) { }
static class OrderEvents {
private final List<Consumer<Order>> onPlaced = new ArrayList<>();
void whenPlaced(Consumer<Order> action) { onPlaced.add(action); }
void place(Order o) {
System.out.println("placed " + o.id());
onPlaced.forEach(action -> action.accept(o));
}
}
public static void main(String[] args) {
OrderEvents events = new OrderEvents();
List<String> outbox = new ArrayList<>();
double highValue = 10_000;
events.whenPlaced(o -> outbox.add("EMAIL to " + o.email() + ": order " + o.id() + " confirmed"));
events.whenPlaced(o -> {
if (o.express()) outbox.add("SMS to " + o.phone() + ": express order " + o.id() + " ships today");
});
events.whenPlaced(o -> {
if (o.amount() >= highValue) outbox.add("SLACK #sales: big order " + o.id() + " from " + o.customer());
});
events.place(new Order("O-1001", "Asha", "+91-90000-11111", "asha@gocourse.in", 2_499, true));
events.place(new Order("O-1002", "Ravi", "+91-90000-22222", "ravi@gocourse.in", 18_750, false));
outbox.forEach(m -> System.out.println(" " + m));
}
}
Output:
placed O-1001
placed O-1002
EMAIL to asha@gocourse.in: order O-1001 confirmed
SMS to +91-90000-11111: express order O-1001 ships today
EMAIL to ravi@gocourse.in: order O-1002 confirmed
SLACK #sales: big order O-1002 from Ravi
How it works:
Consumer<Order>is a functional interface whose methodaccept(Order)returns nothing — the right shape for "do something with this order".whenPlacedstores each lambda in a list. The lambdas are objects that will be called later, when an order is placed.placeruns every registered action withonPlaced.forEach(action -> action.accept(o))— itself a lambda passed toforEach.- Each reaction is independent. The SMS lambda checks
o.express(); the sales alert checks the amount againsthighValue, a captured, effectively final local variable. Lambdas with several statements use a block body{ ... }. - Captured state. All three lambdas add to the same
outboxlist. The variableoutboxis effectively final; the list it refers to is modified, which is allowed. A real application would send the messages through email and SMS services instead of collecting them.
This is the observer pattern. Before Java 8 it required an interface plus a class (or anonymous class) per reaction; with lambdas, each reaction is one short expression next to the others, which is how GUI event handlers, Spring's event listeners and many callback-based APIs are used today.