Lambdas
A lambda is a function written where a value is expected: the body of a method that an interface declares, with no class name and no new. It exists because an interface with one method is the shape Java uses for a piece of behaviour, and before Java 8 every such piece needed an anonymous class of five lines. This lesson writes the same behaviour both ways, so the shorter form is not a trick but a rewrite.
The syntax
name -> "hello " + name is a lambda: the parameters on the left, an arrow, the body on the right. A body of one expression returns its value, and a body of several statements needs braces and a return. The anonymous class below is the same function written the old way:
public class Greeting {
interface Greeter {
String greet(String name);
}
public static void main(String[] args) {
Greeter plain = name -> "hello " + name;
Greeter shout = name -> plain.greet(name).toUpperCase() + "!";
Greeter anonymous = new Greeter() {
@Override
public String greet(String name) {
return "hi " + name;
}
};
System.out.println(plain.greet("Ada"));
System.out.println(shout.greet("Ada"));
System.out.println(anonymous.greet("Ada"));
System.out.println(apply(plain, "Grace"));
}
static String apply(Greeter greeter, String name) {
return greeter.greet(name);
}
}
javac -Xlint:all Greeting.java
java Greeting
hello Ada
HELLO ADA!
hi Ada
hello Grace
shout calls another lambda, which is legal because a lambda is an object and the variable plain is in scope. The last line passes one to a method, which is the use the rest of the course makes: behaviour as an argument. The lambda and the anonymous class produce the same kind of object, and the compiler turns the lambda into a method of the class, which is why the build prints no warning.
A functional interface of your own
A functional interface is an interface with exactly one abstract method. Greeter is one, and the annotation @FunctionalInterface makes the compiler check the count, so a second abstract method added later is a build error rather than a mystery. The JDK has a set of them in java.util.function, and lesson 083 goes through the ones a program actually uses.
A lambda and its interface are not two things: the lambda is an implementation of the interface, and the type is decided by the context. The same body can be a Comparator in one place and a BiFunction in another, because the compiler reads the target type from the assignment or the argument.
Capturing a variable
A lambda may read a local variable of the enclosing method, and that is called a capture. The lambda keeps the value it saw, which is only possible if the variable never changes afterwards, so the compiler requires the variable to be final or effectively final:
public class Capture {
public static void main(String[] args) {
int factor = 3;
Calculator twice = n -> n * 2;
Calculator timesFactor = n -> n * factor;
System.out.println(twice.calculate(5));
System.out.println(timesFactor.calculate(5));
final String suffix = "done";
Runnable task = () -> System.out.println(suffix);
task.run();
}
interface Calculator {
int calculate(int n);
}
}
javac -Xlint:all Capture.java
java Capture
10
15
done
factor is not declared final, but it is assigned once and never again, which is what effectively final means. The suffix is declared final for a reader, and the build treats the two the same. Note that the lambda does not copy the n parameter of calculate: a parameter of the lambda is its own, and only outer variables are captured.
Effectively final
Assign the variable a second time and the lambda that captured it stops compiling, at the use rather than at the assignment:
public class NotFinal {
public static void main(String[] args) {
int factor = 3;
Runnable task = () -> System.out.println(factor);
factor = 4;
task.run();
}
}
javac -Xlint:all NotFinal.java
NotFinal.java:4: error: local variables referenced from a lambda expression must be final or effectively final
Runnable task = () -> System.out.println(factor);
^
1 error
The message names the rule and points at the variable. The reason is the closure: the lambda may run long after the method returned, and it must print one value, so the language does not allow the value to be ambiguous. A variable that really has to change goes in a field, an array of one element or an AtomicInteger, and each of those is a hint that the design should be looked at.
A lambda as an argument
The method below takes a Predicate<String> and returns the words it accepts. Four calls pass four different conditions, and the last two are built from a stored predicate with and and negate:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class Filters {
public static void main(String[] args) {
List<String> words = List.of("pear", "fig", "apple", "kiwi");
System.out.println(filter(words, w -> w.length() > 3));
System.out.println(filter(words, w -> w.startsWith("k")));
Predicate<String> longWord = w -> w.length() > 3;
Predicate<String> startsWithP = w -> w.startsWith("p");
System.out.println(filter(words, longWord.and(startsWithP)));
System.out.println(filter(words, longWord.negate()));
}
static List<String> filter(List<String> words, Predicate<String> keep) {
List<String> result = new ArrayList<>();
for (String word : words) {
if (keep.test(word)) {
result.add(word);
}
}
return result;
}
}
javac -Xlint:all Filters.java
java Filters
[pear, apple, kiwi]
[kiwi]
[pear]
[fig]
The four results are the four conditions: longer than three letters, starting with k, both at once, and the negation of the first. The method has one if and no knowledge of any condition, which is the point of passing behaviour. A stream replaces the loop and the list in lesson 085, and the predicate it takes is the same object.
Exercises
- Write the shout lambda of Greeting as a block with braces and a return.
- Add a second abstract method to Greeter and read the error the annotation gives.
- Capture an array of one element in a lambda, change the element and print it.
- Pass a lambda that keeps the words of an even length to the filter and print the result.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a functional interface?
Answer
An interface with exactly one abstract method
One abstract method is what a lambda implements, and the annotation checks the count.
-
What does a lambda capture?
Answer
Local variables of the enclosing method that are final or effectively final
The lambda keeps the value it saw, so that value must not change afterwards.
-
What does
w -> w.length() > 3return?Answer
A boolean, so it fits a Predicate
The expression is a comparison, which is the shape a Predicate declares.
-
What does this program print?
public class Q1 { interface Op { int apply(int a, int b); } public static void main(String[] args) { Op add = (a, b) -> a + b; Op max = (a, b) -> a > b ? a : b; System.out.println(add.apply(2, 3)); System.out.println(max.apply(2, 3)); } }Answer
5 / 3
The first body adds and the second answers the greater of the two.
-
What does this program print?
public class Q2 { interface Supply { String get(); } public static void main(String[] args) { String name = "Ada"; Supply supply = () -> "hi " + name; System.out.println(supply.get()); } }Answer
hi Ada
The lambda captures the local variable and reads its value when it runs.
-
What is the first line of the compiler output for this program?
public class Q3 { public static void main(String[] args) { int n = 1; Runnable task = () -> System.out.println(n); n = 2; task.run(); } }Answer
error: local variables referenced from a lambda expression must be final or effectively final
The second assignment makes n not effectively final, so the capture is refused.
-
What does this program print?
public class Q4 { interface Calc { int calc(int n); } public static void main(String[] args) { Calc square = n -> n * n; Calc twice = n -> square.calc(n) * 2; System.out.println(twice.calc(3)); } }Answer
18
The first lambda squares three and the second doubles the result.
-
What does this program print?
import java.util.function.Predicate; public class Q5 { public static void main(String[] args) { Predicate<String> empty = String::isEmpty; System.out.println(empty.test("")); System.out.println(empty.negate().test("")); } }Answer
true / false
The empty string satisfies the predicate, and negate turns the answer around.
-
Which annotation makes the compiler check a functional interface?
Answer
@FunctionalInterface
It fails the build when the interface has other than one abstract method.
-
Where does the compiler learn the type of a lambda?
Answer
From the context: the variable, the parameter or the return type it is assigned to
The same body can implement different interfaces, so the target type decides.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev