Java Lambda Variable Scope, Processing Lambdas and Comparator Methods
Go deeper with Java lambdas: closures and effectively final variables, this inside a lambda, writing methods that accept lambdas, the complete java.util.function tables, combining predicates and functions, String.transform, and building comparators with comparing, thenComparing and nullsFirst.
kvi5hnuCode Sprout team member12 min readOn this page
You can now write lambdas and method references. This article covers three remaining topics: what a lambda may access from its surroundings, how to write your own methods that accept lambdas, and the Comparator factory methods you'll use constantly.
Variable Scope
Often you want a lambda to access variables from the enclosing method or class. Consider:
public static void repeatMessage(String text, int delay) {
ActionListener listener = event -> {
System.out.println(text);
Toolkit.getDefaultToolkit().beep();
};
new Timer(delay, listener).start();
}
and a call
repeatMessage("Hello", 1000); // prints Hello every 1,000 milliseconds
Look at text inside the lambda. It isn't defined in the lambda; it's a parameter of repeatMessage. Something non-obvious is going on: the lambda's code may run long after repeatMessage has returned and its parameter variables are gone. How does text stay around?
Closures
We need to refine our understanding of a lambda. It has three ingredients:
- a block of code,
- parameters,
- values for the free variables, the variables that are neither parameters nor defined inside the code.
Here the lambda has one free variable, text. The data structure representing the lambda must store its value, the string "Hello". We say the value has been captured by the lambda. (How that's done is an implementation detail. One way is to translate the lambda into an object with a single method, copying the values of free variables into instance fields of that object.)

The technical term for a block of code together with the values of its free variables is a closure. If someone gloats that their language has closures, rest assured that Java has them too: Java lambdas are closures.
Captured variables must be effectively final
To keep captured values well-defined, Java imposes an important restriction: a lambda can only reference variables whose values don't change. This is illegal:
public static void countDown(int start, int delay) {
ActionListener listener = event -> {
start--; // ERROR: can't mutate captured variable
System.out.println(start);
};
new Timer(delay, listener).start();
}
There's a reason: mutating variables in a lambda isn't safe when several actions run concurrently. That doesn't happen with the actions we've seen so far, but in general it's a serious problem (see the concurrency part).
It's also illegal to refer to a variable that's mutated outside the lambda:
public static void repeat(String text, int count) {
for (int i = 1; i <= count; i++) {
ActionListener listener = event -> {
System.out.println(i + ": " + text); // ERROR: can't refer to changing i
};
new Timer(1000, listener).start();
}
}
Both give local variables referenced from a lambda expression must be final or effectively final. The rule: any captured local variable must be effectively final, meaning it's never assigned a new value after initialization. Here text always refers to the same String, so capturing it is fine. But i changes, so it can't be captured.
Common fixes:
- Copy the changing value into a fresh local variable inside the loop:
int n = i;and capturen. - Use an enhanced
forloop:for (String name : names)creates a new effectively final variable on each iteration, so lambdas can capture it. - If you really need mutable state, keep it in an object (an
AtomicInteger, a field, or an array element as in the demo). Then the captured reference doesn't change, only the object does. Be aware that this isn't thread-safe unless the object is.
Same scope as a nested block
The body of a lambda has the same scope as a nested block. The usual rules for name conflicts and shadowing apply. It's illegal to declare a parameter or local variable in the lambda with the same name as a local variable of the enclosing method:
Path first = Path.of("/usr/bin");
Comparator<String> comp
= (first, second) -> first.length() - second.length();
// ERROR: variable first is already defined
Inside a method you can't have two local variables with the same name, so you can't introduce one in a lambda either. (The unnamed _ is the exception: it never conflicts.)
this in a lambda
When you use this in a lambda, it refers to the this of the method that creates the lambda:
public class Application {
public void init() {
ActionListener listener = event -> {
System.out.println(this.toString());
. . .
};
. . .
}
}
this.toString() calls toString of the Application object, not of the ActionListener. There's nothing special about this in a lambda: the lambda's scope is nested inside init, and this means the same thing anywhere in that method. (Anonymous inner classes, covered later, behave differently: there this is the inner object.)
Processing Lambda Expressions
So far you've produced lambdas and passed them to methods that expect functional interfaces. Now let's write methods that consume them.
The point of using lambdas is deferred execution. After all, if you wanted to run some code right now, you'd just run it, without wrapping it in a lambda. There are many reasons to execute code later:
- running it in a separate thread,
- running it multiple times,
- running it at the right point in an algorithm (such as the comparison in sorting),
- running it when something happens (a button click, data arriving),
- running it only when necessary.
Suppose you want to repeat an action n times, passing the action and count to a repeat method:
repeat(10, () -> System.out.println("Hello, World!"));
To accept the lambda, pick (or, rarely, provide) a functional interface. Here Runnable fits:
public static void repeat(int n, Runnable action) {
for (int i = 0; i < n; i++) action.run();
}
The lambda's body runs when action.run() is called.
Now let's tell the action which iteration it's in. We need a functional interface with an int parameter and a void return. The standard one is
public interface IntConsumer {
void accept(int value);
}
and the improved repeat is
public static void repeat(int n, IntConsumer action) {
for (int i = 0; i < n; i++) action.accept(i);
}
repeat(10, i -> System.out.println("Countdown: " + (9 - i)));
The standard functional interfaces
Common functional interfaces:
| Functional interface | Parameter types | Return type | Abstract method | Other methods |
|---|---|---|---|---|
Runnable | none | void | run | |
Supplier<T> | none | T | get | |
Consumer<T> | T | void | accept | andThen |
BiConsumer<T, U> | T, U | void | accept | andThen |
Function<T, R> | T | R | apply | compose, andThen, identity |
BiFunction<T, U, R> | T, U | R | apply | andThen |
UnaryOperator<T> | T | T | apply | compose, andThen, identity |
BinaryOperator<T> | T, T | T | apply | andThen, maxBy, minBy |
Predicate<T> | T | boolean | test | and, or, negate, isEqual, not |
BiPredicate<T, U> | T, U | boolean | test | and, or, negate |
Specializations for primitive types (34 in total). Here p, q stand for int, long, double, and P, Q for Int, Long, Double:
| Functional interface | Parameter types | Return type | Abstract method |
|---|---|---|---|
BooleanSupplier | none | boolean | getAsBoolean |
PSupplier | none | p | getAsP |
PConsumer | p | void | accept |
ObjPConsumer<T> | T, p | void | accept |
PFunction<T> | p | T | apply |
PToQFunction | p | q | applyAsQ |
ToPFunction<T> | T | p | applyAsP |
ToPBiFunction<T, U> | T, U | p | applyAsP |
PUnaryOperator | p | p | applyAsP |
PBinaryOperator | p, p | p | applyAsP |
PPredicate | p | boolean | test |
For example, IntToLongFunction, ToDoubleBiFunction<T, U> and LongPredicate. The specializations avoid boxing and are more efficient than the generic interfaces, which is why repeat uses IntConsumer instead of Consumer<Integer>.
Combining functions
Most standard functional interfaces have non-abstract methods for producing or combining functions:
Predicate.isEqual(a)is the same asa::equals, but also works ifaisnull.and,orandnegatecombine predicates:Predicate.isEqual(a).or(Predicate.isEqual(b))is the same asx -> a.equals(x) || b.equals(x).Predicate.not(p)(Java 11) negates a method reference:filter(Predicate.not(String::isBlank)).f.andThen(g)appliesffirst, theng;f.compose(g)appliesgfirst.Function.identity()returns its argument.
String.transform
Some programmers love chains of method calls:
String input = " 618970019642690137449562111 ";
boolean isPrime = input.strip().transform(BigInteger::new).isProbablePrime(20);
String.transform (Java 12) applies a Function to the string and returns the result. You could equally write
boolean prime = new BigInteger(input.strip()).isProbablePrime(20);
but then your eyes jump inside-out and left-to-right to see what happens first: calling strip, constructing the BigInteger, then testing primality. With transform, the steps read in order.
Sadly, it only works for strings. Why isn't there a transform(Function) method in Object? The API designers had exactly one chance: Java 8, when java.util.function.Function was introduced. Before that, nobody could have defined such a method in their own classes. By Java 12 it was too late, because someone somewhere might have defined transform(Function) in a class with a different meaning. It's unlikely, but there's no way to know. That's how Java works: it takes its compatibility commitments seriously and won't renege on them for convenience.
Creating Comparators
The Comparator interface has many convenient static and default methods for creating comparators, intended for use with lambdas and method references.
The static comparing method takes a key extractor function that maps a type T to a comparable type such as String. The function is applied to the objects being compared, and the comparison is made on the returned keys. To sort an array of Person objects by name:
Arrays.sort(people, Comparator.comparing(Person::getName));
That's much easier than implementing a Comparator by hand, and clearer: it's obvious that we compare people by name.
Chain comparators with thenComparing to break ties:
Arrays.sort(people,
Comparator.comparing(Person::getLastName)
.thenComparing(Person::getFirstName));
If two people have the same last name, the second comparator is used.
There are variations. You can give comparing and thenComparing a comparator for the extracted keys. Here we sort people by the length of their names:
Arrays.sort(people, Comparator.comparing(Person::getName,
(s, t) -> Integer.compare(s.length(), t.length())));
Both methods also have variants that avoid boxing int, long or double keys:
Arrays.sort(people, Comparator.comparing(Person::getName,
Comparator.comparingInt(String::length)));
A shorter, if less elegant, way to write the same:
Arrays.sort(people, Comparator.comparingInt(p -> p.getName().length()));
Handling null keys
If your key function can return null, use the nullsFirst and nullsLast adapters. They take an existing comparator and modify it so that it doesn't throw on null values, but ranks them as smaller or larger than regular values. Suppose getMiddleName returns null when a person has no middle name:
Comparator.comparing(Person::getMiddleName, Comparator.nullsFirst(. . .))
nullsFirst needs a comparator for the strings themselves. naturalOrder makes a comparator for any class implementing Comparable. Comparator.<String>naturalOrder() is what we need; the explicit type argument syntax is explained in the generics part, and fortunately the type can usually be inferred. With a static import of java.util.Comparator.*, the complete call is readable:
Arrays.sort(people, comparing(Person::getMiddleName, nullsFirst(naturalOrder())));
Reversing
The static reverseOrder method gives the reverse of the natural order. To reverse any comparator, use the reversed instance method: naturalOrder().reversed() is the same as reverseOrder().
| Method | Kind | Purpose |
|---|---|---|
comparing(keyExtractor) | static | Compare by a Comparable key |
comparing(keyExtractor, keyComparator) | static | Compare by a key with a custom comparator |
comparingInt/Long/Double(keyExtractor) | static | Primitive keys without boxing |
thenComparing(...), thenComparingInt(...) | default | Tie-breakers |
reversed() | default | Reverse this comparator |
naturalOrder(), reverseOrder() | static | Natural order and its reverse |
nullsFirst(c), nullsLast(c) | static | Tolerate null values |
Everything in One Program
import java.math.BigInteger;
import java.util.*;
import java.util.function.*;
import static java.util.Comparator.*;
public class Solution {
public static void main(String[] args) {
// --- capturing variables: closures ---
Runnable hello = makeRepeater("Hello", 2);
hello.run(); // makeRepeater has returned, but text and count live on
// effectively final: each iteration gets a fresh variable in an enhanced for loop
List<Runnable> actions = new ArrayList<>();
for (String name : List.of("Ada", "Linus")) actions.add(() -> System.out.println("Hi " + name));
for (int i = 1; i <= 2; i++) {
int n = i; // copy the changing loop variable into an effectively final one
actions.add(() -> System.out.println("Action " + n));
}
actions.forEach(Runnable::run);
// mutable state belongs in an object, not in a captured local variable
int[] counter = { 0 };
repeat(3, () -> counter[0]++);
System.out.println("counter = " + counter[0]);
// this inside a lambda is the enclosing object
new Application().init();
// --- processing lambdas: deferred execution ---
repeat(2, () -> System.out.println("Hello, World!"));
repeat(3, i -> System.out.println("Countdown: " + (2 - i)));
// combining predicates
Predicate<String> isA = Predicate.isEqual("a");
Predicate<String> isNull = Predicate.isEqual(null); // works with null, unlike null::equals
Predicate<String> aOrNull = isA.or(isNull);
Predicate<String> notBlank = Predicate.not(String::isBlank);
System.out.println(aOrNull.test("a") + " " + aOrNull.test(null) + " " + aOrNull.negate().test("b")
+ " " + notBlank.and(s -> s.length() < 4).test("abc"));
// composing functions
Function<Integer, Integer> plus1 = x -> x + 1;
Function<Integer, Integer> times2 = x -> x * 2;
System.out.println(plus1.andThen(times2).apply(5) + " " + plus1.compose(times2).apply(5));
// String.transform: left-to-right chains
String input = " 618970019642690137449562111 ";
boolean isPrime = input.strip().transform(BigInteger::new).isProbablePrime(20);
System.out.println(isPrime);
// --- creating comparators ---
var people = new Person[] {
new Person("Grace", null, "Hopper"),
new Person("Ada", "King", "Lovelace"),
new Person("Alan", "Mathison", "Turing"),
new Person("Adele", null, "Goldberg"),
new Person("Barbara", null, "Liskov"),
new Person("Ada", null, "Byron") };
Arrays.sort(people, comparing(Person::firstName));
print("by first name (stable)", people);
Arrays.sort(people, comparing(Person::firstName).thenComparing(Person::lastName));
print("first, then last", people);
Arrays.sort(people, comparing(Person::lastName, (s, t) -> Integer.compare(s.length(), t.length())));
print("by last name length", people);
Arrays.sort(people, comparingInt(p -> p.lastName().length()));
print("same, comparingInt", people);
Arrays.sort(people, comparing(Person::middleName, nullsFirst(naturalOrder())));
print("middle name, nulls first", people);
Arrays.sort(people, comparing(Person::lastName, reverseOrder()));
print("last name reversed", people);
Arrays.sort(people, comparing(Person::firstName).reversed().thenComparing(Person::lastName));
print("first desc, last asc", people);
}
static Runnable makeRepeater(String text, int count) {
return () -> { // captures text and count
for (int i = 0; i < count; i++) System.out.println(text);
};
}
public static void repeat(int n, Runnable action) {
for (int i = 0; i < n; i++) action.run();
}
public static void repeat(int n, IntConsumer action) {
for (int i = 0; i < n; i++) action.accept(i);
}
static void print(String label, Person[] people) {
var sj = new StringJoiner(", ", label + ": ", "");
for (Person p : people) sj.add(p.toString());
System.out.println(sj);
}
}
record Person(String firstName, String middleName, String lastName) {
@Override public String toString() {
return firstName + (middleName == null ? "" : " " + middleName.charAt(0) + ".") + " " + lastName;
}
}
class Application {
private final String name = "the Application object";
public void init() {
Runnable r = () -> System.out.println("this is " + this); // not the Runnable
r.run();
}
@Override public String toString() { return name; }
}
Hello
Hello
Hi Ada
Hi Linus
Action 1
Action 2
counter = 3
this is the Application object
Hello, World!
Hello, World!
Countdown: 2
Countdown: 1
Countdown: 0
true true true true
12 11
true
by first name (stable): Ada K. Lovelace, Ada Byron, Adele Goldberg, Alan M. Turing, Barbara Liskov, Grace Hopper
first, then last: Ada Byron, Ada K. Lovelace, Adele Goldberg, Alan M. Turing, Barbara Liskov, Grace Hopper
by last name length: Ada Byron, Alan M. Turing, Barbara Liskov, Grace Hopper, Ada K. Lovelace, Adele Goldberg
same, comparingInt: Ada Byron, Alan M. Turing, Barbara Liskov, Grace Hopper, Ada K. Lovelace, Adele Goldberg
middle name, nulls first: Ada Byron, Barbara Liskov, Grace Hopper, Adele Goldberg, Ada K. Lovelace, Alan M. Turing
last name reversed: Alan M. Turing, Ada K. Lovelace, Barbara Liskov, Grace Hopper, Adele Goldberg, Ada Byron
first desc, last asc: Grace Hopper, Barbara Liskov, Alan M. Turing, Adele Goldberg, Ada Byron, Ada K. Lovelace
Notice that the first sort keeps "Ada K. Lovelace" before "Ada Byron": object sorting is stable, so equal keys keep their previous order. The thenComparing sort fixes that tie.
Common questions
Why must captured local variables be effectively final? The lambda captures a copy of the value, and it may run later or on another thread. If the variable could still change, the copy and the variable would disagree, and concurrent changes would be unsafe. Requiring effectively final variables makes the copy indistinguishable from the original.
How do I count something inside a lambda?
Prefer a stream operation that returns the result: count(), sum(), reduce or collect. If you really need a mutable counter, use an AtomicInteger or a field, but then you must think about thread safety. Lambdas that modify outer state are a code smell in stream pipelines.
What does this mean inside a lambda?
The same as in the surrounding method: the enclosing object. A lambda doesn't introduce a new this. In an anonymous class, by contrast, this refers to the anonymous object itself.
How do I sort by one key descending and another ascending?
Reverse only that key's comparator: Comparator.comparing(Person::age, Comparator.reverseOrder()).thenComparing(Person::name). Calling .reversed() at the end reverses the whole chain built so far.
Should my API accept Function<T, R> or my own interface?
Use the standard interfaces when they fit, so callers can combine them with andThen, compose, Predicate.not and so on. Define your own @FunctionalInterface when the method needs checked exceptions, more parameters than the standard interfaces support, or a name that explains its purpose better.
Summary
- Lambdas are closures: they capture the values of free variables from the enclosing scope, and those values outlive the method call.
- Captured local variables must be effectively final. Copy loop variables into fresh locals, or keep mutable state in objects.
- A lambda body has the scope of a nested block: no shadowing of local variables, and
thismeans the enclosing object. - To accept a lambda, declare a parameter of a functional interface type, preferably a standard one from
java.util.function, and use primitive specializations to avoid boxing. PredicateandFunctionhave combinators (and,or,negate,not,isEqual,andThen,compose).- Build comparators with
comparing,thenComparing,comparingInt,nullsFirst/nullsLast,naturalOrder,reverseOrderandreversed.
Practice Questions
Why doesn't int count = 0; list.forEach(s -> count++); compile, and what are two fixes?
count is a captured local variable that's modified, so it isn't effectively final. Use list.size() or a stream's count(), or keep the counter in an object such as an AtomicInteger or an int[1].
for (int i = 0; i < 3; i++) tasks.add(() -> System.out.println(i)); doesn't compile. Fix it.
Copy the loop variable into an effectively final local: for (int i = 0; i < 3; i++) { int n = i; tasks.add(() -> System.out.println(n)); }
Inside a lambda in an instance method of class Order, what does this refer to?
The Order object on which the method was called. A lambda doesn't introduce its own this.
Write a method twice(Function<Integer, Integer> f, int x) that applies f two times, and call it to compute 3 + 10 + 10.
static int twice(Function<Integer, Integer> f, int x) {
return f.andThen(f).apply(x);
}
int result = twice(v -> v + 10, 3); // 23
Sort a List<Employee> by department ascending, then salary descending, with Comparator methods.
staff.sort(Comparator.comparing(Employee::getDepartment)
.thenComparing(Comparator.comparingDouble(Employee::getSalary).reversed()));
What's the difference between Predicate.isEqual(x) and x::equals when x is null?
x::equals throws a NullPointerException when it's created. Predicate.isEqual(null) works and tests whether its argument is null.
Related reading
- Java Lambda Expressions and Functional Interfaces
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
- Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()
- Java Optional: Getting, Consuming and Transforming Optional Values

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.