#Lambdas and functional interfaces
AddedIn JavaScript a function is a value: const isLong = s => s.length > 4 and you pass isLong around. Java has no function type. Instead, a lambda is a short way to write an object that implements an interface with exactly one abstract method, called a functional interface. Predicate<String> isLong = s -> s.length() > 4; creates an object whose test method runs s.length() > 4. You call it by its method name: isLong.test("mouse"), not isLong("mouse").
Before Java 8 you wrote the same thing as an anonymous inner class, five lines for one expression (chapter 01 shows one). A lambda is that class with the ceremony removed, and the compiler works out which interface it implements from where you use it (the target type). java.util.function has the standard shapes, so you rarely declare your own:
| Interface | Method | Shape | Example |
|---|---|---|---|
Function<T, R> | apply | T → R | s -> s.length() |
BiFunction<T, U, R> | apply | (T, U) → R | (a, b) -> a + b |
Predicate<T> | test | T → boolean | s -> s.isEmpty() |
Supplier<T> | get | () → T | () -> new ArrayList<>() |
Consumer<T> | accept | T → nothing | s -> IO.println(s) |
UnaryOperator<T> / BinaryOperator<T> | apply | T → T / (T, T) → T | s -> s.strip(), Integer::sum |
There are also primitive versions (IntPredicate, ToIntFunction, IntBinaryOperator, …) that avoid boxing int into Integer. The mental model: a lambda is a one-method object, and the interface's name tells you how to call it. The one rule that surprises JavaScript developers comes next: a lambda can read local variables from the surrounding method only if they're effectively final, never reassigned after they're set.
@FunctionalInterface
interface PriceRule {
double apply(double price);
}
void main() {
Function<String, Integer> length = s -> s.length();
Predicate<String> isLong = s -> s.length() > 4;
Supplier<List<String>> fresh = () -> new ArrayList<>();
Consumer<String> shout = s -> IO.println(s.toUpperCase() + "!");
BinaryOperator<Integer> add = (a, b) -> a + b;
IO.println(length.apply("keyboard") + " " + isLong.test("mouse") + " " + isLong.negate().test("mouse"));
shout.accept("hello");
IO.println(add.apply(2, 3));
List<String> list = fresh.get();
list.add("new");
IO.println(list + " " + (fresh.get() != list));
Function<String, String> clean = s -> s.strip();
Function<String, Integer> cleanLength = clean.andThen(length);
IO.println(cleanLength.apply(" mouse "));
PriceRule tenOff = price -> price * 0.9;
PriceRule minusFive = price -> price - 5;
double price = 100;
IO.println(minusFive.apply(tenOff.apply(price)));
}$ java Functions.java
8 true false
HELLO!
5
[new] true
5
85.0- Each lambda becomes an object of its target interface:
length.apply("keyboard")runss.length()and returns8;isLong.test("mouse")istrue(5 > 4), andnegate(), a default method onPredicate, gives the opposite:false. shout.accept("hello")printsHELLO!; aConsumerreturns nothing.add.apply(2, 3)gives5.freshis aSupplier: everyget()runs the lambda again and builds a new list, which is why the secondget()isn't the same object aslist(true).andThencomposes functions, like piping in JavaScript:clean.andThen(length)strips first, then measures." mouse "becomes"mouse", length5.PriceRuleis our own functional interface;@FunctionalInterfaceis optional, but it makes the compiler reject the interface if someone adds a second abstract method.tenOffthenminusFiveturns 100 into 90.0 and then 85.0.- Note how each call uses the interface's method name (
apply,test,get,accept). That's the price of Java having no function types: the lambda is short, but the type that receives it decides how it's called.
A JavaScript arrow function can change any variable it can see. A Java lambda can read local variables of the enclosing method, but only if they're effectively final: assigned once and never changed. The lambda gets a copy of the value, not the variable, so letting either side change it would make the copy and the variable disagree.
void main() {
int count = 0;
List.of("a", "b", "c").forEach(s -> count++);
IO.println(count);
}$ java Counter.java
Counter.java:3: error: local variables referenced from a lambda expression must be final or effectively final
List.of("a", "b", "c").forEach(s -> count++);
^
1 error
error: compilation failedlet count = 0;
["a", "b", "c"].forEach(() => count++);
console.log(count);$ node counter.mjs
3- Java:
count++inside the lambda would change a local variable ofmain, and the compiler refuses: "local variables referenced from a lambda expression must be final or effectively final". - JavaScript: the arrow function closes over the variable itself, so all three calls increment the same
countand it prints3. - The Java way is to not need the mutation:
long count = list.stream().count();, orfilter(…).count()for a condition. When you truly need a mutable counter inside a lambda (rare), anAtomicIntegeror a field works, because the lambda then captures a reference that stays the same while the object it points to changes. - Fields are different from local variables: a lambda in an instance method can read and change the object's fields freely, because it captures
this, which never changes.
A lambda doesn't create a new scope for this: inside it, this means the enclosing object, like an arrow function in JavaScript. An anonymous class is a real new object, so its this is itself. This is a common interview contrast.
public class Greeter {
private final String name = "greeter";
public String toString() {
return "the Greeter";
}
void run() {
Runnable lambda = () -> System.out.println("lambda this: " + this + ", name " + name);
Runnable anonymous = new Runnable() {
public void run() {
System.out.println("anonymous this: " + this.getClass().getSimpleName().isEmpty() + ", name " + name);
}
};
lambda.run();
anonymous.run();
}
public static void main(String[] args) {
new Greeter().run();
}
}$ java Greeter.java
lambda this: the Greeter, name greeter
anonymous this: true, name greeter- In the lambda,
thisis theGreeterwhoseruncreated it, so it printsthe Greeter(itstoString()). - In the anonymous class,
thisis the anonymousRunnableobject. Anonymous classes have an empty simple name, which is whatisEmpty()shows (true). It can still readname, through the hidden reference every inner class keeps to its outer object. - That hidden reference is why an anonymous class (or inner class) kept alive by a long-lived listener can keep its whole outer object from being garbage-collected. A lambda captures
thisonly if its body usesthisor a field:javap -pon a compiled class shows a lambda that reads a field compiled to an instance method, and one that doesn't to astaticmethod. - JavaScript parallel: an arrow function behaves like the lambda (
thisfrom the surrounding code), afunction () {}callback like the anonymous class (its ownthis).
void main() {
List<Supplier<Integer>> suppliers = new ArrayList<>();
for (int i = 0; i < 3; i++) {
suppliers.add(() -> i * 10);
}
suppliers.forEach(s -> IO.println(s.get()));
}Show answer
void main() {
List<Supplier<Integer>> suppliers = new ArrayList<>();
for (int i = 0; i < 3; i++) {
suppliers.add(() -> i * 10);
}
suppliers.forEach(s -> IO.println(s.get()));
}$ java Loop.java
Loop.java:4: error: local variables referenced from a lambda expression must be final or effectively final
suppliers.add(() -> i * 10);
^
1 error
error: compilation failed- No. A classic
forloop has one variableithati++changes, so it isn't effectively final, and the lambda can't capture it. - JavaScript with
var iis the famous bug where every callback sees the final value;let imakes a fresh binding per iteration. Java simply refuses to compile the ambiguous case. - The fix is a fresh variable per iteration,
int copy = i;, which is never changed, so the lambda can capture it. An enhancedforloop also works, because its variable is new for each iteration. Both are below.
void main() {
List<Supplier<Integer>> suppliers = new ArrayList<>();
for (int i = 0; i < 3; i++) {
int copy = i;
suppliers.add(() -> copy * 10);
}
for (int n : List.of(3, 4)) {
suppliers.add(() -> n * 10);
}
suppliers.forEach(s -> IO.println(s.get()));
}$ java Loop.java
0
10
20
30
40- Each lambda captured its own
copyorn, so the values are0,10,20,30,40.