JAVA-230 · Lesson 1 of 12 · 22 min
Lambdas and functional interfaces
▶ Video coming soon A video version of this lesson is on the way.
On Wednesday, September 15, 2027, Hamza opened the shop's back room for the first evening of a new course with Ingrid. The term had already given him algorithms on Tuesdays and testing on Thursdays; Wednesdays were for what Ingrid called "Java as people write it now". She started with a question from his own code. PartsDesk, the parts tool he wrote in 2026, had three methods that walked the parts list: one found parts below their reorder level, one found parts from a single supplier and one found parts on a given shelf. Each was the same loop with a different if inside. "The only thing that changes is the test," she said. "So pass the test in." That is the idea behind a lambda: a small piece of behavior that you can hand to a method, store in a variable or return from a method, just like a value.
Behavior as a value
Before Java 8, the way to pass behavior was to write a class that implemented an interface, then pass an object of that class. An anonymous class shortened this a little, but it still took five or six lines to say "the quantity is below the reorder level". A lambda expression says the same thing in one line. The compiler turns it into an object that implements an interface, so nothing new happens at run time; what changes is how much code you have to write and read.
A lambda has a parameter list, an arrow and a body. The body can be a single expression, whose value is returned, or a block in braces with ordinary statements and a return. Parameter types are usually left out because the compiler infers them from the interface the lambda is assigned to.
| Form | Example | Notes |
|---|---|---|
| No parameters | () -> "ready" | Empty parentheses are required |
| One parameter | p -> p.quantity() < 5 | Parentheses may be left out |
| Two parameters | (a, b) -> a + b | Parentheses are required |
| Typed parameters | (Part p) -> p.code() | Allowed, rarely needed |
| Block body | p -> { int q = p.quantity(); return q < 5; } | Needs return if a value is expected |
| var parameters | (var a, var b) -> a * b | Useful when you want an annotation on a parameter |
import java.util.*;
public class Main {
record Part(String code, String supplier, int quantity, int reorderAt) { }
interface PartTest {
boolean test(Part p);
}
static List<Part> select(List<Part> parts, PartTest rule) {
List<Part> out = new ArrayList<>();
for (Part p : parts) {
if (rule.test(p)) out.add(p);
}
return out;
}
public static void main(String[] args) {
List<Part> parts = List.of(
new Part("TUBE-700x25", "Velotek", 3, 10),
new Part("PAD-ROAD", "Velotek", 14, 6),
new Part("CHAIN-11", "Kessler", 2, 4),
new Part("BELL", "Kessler", 25, 5));
// The old way: an anonymous class
PartTest lowOld = new PartTest() {
@Override
public boolean test(Part p) {
return p.quantity() < p.reorderAt();
}
};
// The new way: a lambda
PartTest low = p -> p.quantity() < p.reorderAt();
PartTest kessler = p -> p.supplier().equals("Kessler");
System.out.println("Low (anonymous class): " + select(parts, lowOld).size());
for (Part p : select(parts, low)) System.out.println("Low: " + p.code());
for (Part p : select(parts, kessler)) System.out.println("Kessler: " + p.code());
}
}Low (anonymous class): 2 Low: TUBE-700x25 Low: CHAIN-11 Kessler: CHAIN-11 Kessler: BELL
What this code does
One select method replaces the three loops PartsDesk used to have, because the test is passed in as a PartTest. The anonymous class and the lambda do exactly the same job, which the matching count shows, but the lambda takes one line instead of six. Any new rule, such as parts from one supplier, is now just another lambda rather than another method.
Read the figure from the bottom up. The variable's type, Predicate<Part>, is what tells the compiler that p is a Part and that the body must produce a boolean. The same text, p -> p.quantity() < p.reorderAt(), would not compile if it were assigned to a Function<Part, String>, because the body does not produce a String. A lambda never stands alone: its meaning always comes from the place it is used.
Functional interfaces
A lambda needs a target: an interface with exactly one abstract method, called a functional interface. PartTest above is one. The interface may also have default and static methods, and methods that Object already provides, such as equals, do not count; what matters is that there is one method left to implement. The annotation @FunctionalInterface is optional, but it asks the compiler to check that rule, so a teammate cannot later add a second abstract method and break every lambda that uses the interface.
Most of the time you do not need to write your own. The package java.util.function has about forty ready-made functional interfaces, and the rest of the Java library, including the Stream API in lesson 3, is written in terms of them. Six of them cover most needs.
| Interface | Method | Takes | Returns | Shop example |
|---|---|---|---|---|
| Predicate<T> | test | a T | boolean | is this part low? |
| Function<T, R> | apply | a T | an R | part to its code |
| Consumer<T> | accept | a T | nothing | print a label |
| Supplier<T> | get | nothing | a T | make a new empty order |
| UnaryOperator<T> | apply | a T | a T | add 13 to a count |
| BinaryOperator<T> | apply | two Ts | a T | add two totals |
There are also two-argument versions (BiFunction, BiPredicate, BiConsumer) and versions for primitives that avoid boxing, such as IntPredicate, ToIntFunction, IntUnaryOperator and IntBinaryOperator. When a lambda works with int values in a loop that runs many times, the primitive versions save the cost of wrapping each int in an Integer object.
import java.util.function.*;
public class Main {
record Part(String code, int quantity, long priceCents) { }
public static void main(String[] args) {
Part tube = new Part("TUBE-700x25", 3, 899);
Predicate<Part> low = p -> p.quantity() < 5;
Function<Part, String> label = p -> p.code() + " x" + p.quantity();
Consumer<String> print = s -> System.out.println("[label] " + s);
Supplier<Part> blank = () -> new Part("NEW", 0, 0);
UnaryOperator<Integer> addCase = n -> n + 10;
BinaryOperator<Long> add = (a, b) -> a + b;
ToLongFunction<Part> stockValue = p -> p.quantity() * p.priceCents();
System.out.println("Low? " + low.test(tube));
print.accept(label.apply(tube));
System.out.println("Blank part: " + blank.get());
System.out.println("After a case arrives: " + addCase.apply(tube.quantity()));
System.out.println("Two totals: " + add.apply(2697L, 650L));
System.out.println("Stock value in cents: " + stockValue.applyAsLong(tube));
}
}Low? true [label] TUBE-700x25 x3 Blank part: Part[code=NEW, quantity=0, priceCents=0] After a case arrives: 13 Two totals: 3347 Stock value in cents: 2697
What this code does
Each variable holds a lambda typed by one of the standard interfaces, and each is called through that interface's single method: test, apply, accept, get or applyAsLong. The method names differ, which is the price of having many interfaces, but every one is a single call. ToLongFunction returns a primitive long, so the stock value of 3 tubes at 899 cents is computed without creating a Long object.
Combining small rules
Several of the standard interfaces have default methods that combine lambdas into bigger ones. A Predicate has and, or and negate, plus the static Predicate.not. A Function has andThen, which runs another function on the result, and compose, which runs another function first. Comparator, which you met in JAVA-201, has the same style: Comparator.comparing(...).thenComparing(...). Building rules from small named pieces keeps each piece easy to test and lets the reader see the rule in words.
import java.util.*;
import java.util.function.*;
public class Main {
record Part(String code, String supplier, int quantity, int reorderAt, boolean discontinued) { }
public static void main(String[] args) {
List<Part> parts = List.of(
new Part("TUBE-700x25", "Velotek", 3, 10, false),
new Part("TUBE-26x2", "Velotek", 1, 6, true),
new Part("CHAIN-11", "Kessler", 2, 4, false),
new Part("PAD-ROAD", "Velotek", 14, 6, false));
Predicate<Part> low = p -> p.quantity() < p.reorderAt();
Predicate<Part> discontinued = Part::discontinued;
Predicate<Part> fromVelotek = p -> p.supplier().equals("Velotek");
Predicate<Part> toOrder = low.and(Predicate.not(discontinued));
Function<Part, Integer> shortBy = p -> p.reorderAt() - p.quantity();
Function<Part, String> orderLine = shortBy.andThen(n -> "order " + n);
for (Part p : parts) {
if (toOrder.test(p)) System.out.println(p.code() + ": " + orderLine.apply(p));
}
System.out.println("Velotek and low: " + parts.stream().filter(fromVelotek.and(low)).count());
System.out.println("Not low: " + parts.stream().filter(low.negate()).count());
}
}TUBE-700x25: order 7 CHAIN-11: order 2 Velotek and low: 2 Not low: 1
What this code does
The ordering rule is built from two smaller predicates, low and not discontinued, so a discontinued tube that is also low is correctly left off the order. orderLine chains two functions with andThen: the first works out how many parts are missing and the second turns that number into text. The last two lines preview lesson 3 by passing combined predicates to a stream's filter method.
What a lambda can see
A lambda can use its own parameters, fields of the object it is written in, and local variables from the method around it. Local variables come with a rule: they must be effectively final, meaning they are never assigned again after they are first given a value. The lambda captures the value, not the variable, so letting the variable change later would be confusing, and with threads it would be unsafe. If you need a value that changes, compute it before the lambda, or keep it in a field or in an object such as an AtomicInteger designed for the purpose.
import java.util.function.*;
public class Main {
public static void main(String[] args) {
int threshold = 5;
Predicate<Integer> low = q -> q < threshold;
threshold = 8;
System.out.println(low.test(6));
}
}What this code does
threshold is assigned again after the lambda captures it, so it is no longer effectively final and the program does not compile. The compiler points at the use inside the lambda, not at the later assignment, which can be puzzling the first time you see it. Removing the second assignment, or copying the value into a new final variable before the lambda, fixes the error.
$ javac Main.java
Main.java:6: error: local variables referenced from a lambda expression must be final or effectively final
Predicate<Integer> low = q -> q < threshold;
^
1 errorInside a lambda, this means the object around it, not the lambda; a lambda has no identity of its own. That is different from an anonymous class, where this is the anonymous object. A lambda also cannot declare a local variable with the same name as one in the enclosing method, because it shares that method's scope.
When a lambda is the wrong tool
Lambdas are best short. Once a body passes three or four lines, give it a name: write a private method and refer to it, which lesson 2 shows how to do with a method reference. A named method can be tested on its own and appears with its name in stack traces, while a long lambda shows up under a generated name made from the word lambda, the method name and a number. Lambdas also cannot throw checked exceptions unless the functional interface declares them, which matters for file work in lesson 7. Keep lambdas free of side effects where you can: a Predicate that also changes a counter or prints a line is hard to reason about when a library calls it more than once, or not at all.
import java.util.*;
import java.util.function.*;
public class Main {
record Booking(int number, String bike, int days) { }
static boolean isLongRental(Booking b) {
return b.days() >= 7;
}
public static void main(String[] args) {
List<Booking> bookings = List.of(
new Booking(1001, "CITY-1", 2), new Booking(1002, "CARGO-1", 7),
new Booking(1003, "TANDEM-1", 3), new Booking(1004, "CITY-3", 9));
int[] calls = {0};
Predicate<Booking> noisy = b -> { calls[0]++; return b.days() >= 7; };
Predicate<Booking> clean = Main::isLongRental;
long first = bookings.stream().filter(noisy).count();
boolean any = bookings.stream().anyMatch(noisy);
System.out.println("Long rentals: " + first + ", any: " + any);
System.out.println("The noisy predicate ran " + calls[0] + " times");
System.out.println("Clean predicate agrees: " + bookings.stream().filter(clean).count());
}
}Long rentals: 2, any: true The noisy predicate ran 6 times Clean predicate agrees: 2
What this code does
The noisy predicate counts its own calls through a one-element array, a common trick to get around the effectively final rule. It ran six times, four for the count and only two for anyMatch, which stopped as soon as it found a match, so a side effect inside a lambda depends on how the library chooses to call it. The clean version is a named method referred to with Main::isLongRental, which is easier to test and to read.
By the end of the evening Hamza had replaced the three PartsDesk loops with one method and three short lambdas, and Ingrid asked him to keep a list of lambdas that grew past three lines. "Those are the ones that want names," she said, which set up the next week's topic.
Try it yourself
Rules for the reorder list
The program has a list of parts and an empty rule. Build rule from the predicates low and discontinued so that only parts that are low **and not** discontinued are kept.
The program should then print TUBE-700x25 and CHAIN-11, one per line.
import java.util.*;
import java.util.function.*;
public class Main {
record Part(String code, int quantity, int reorderAt, boolean discontinued) { }
public static void main(String[] args) {
List<Part> parts = List.of(
new Part("TUBE-700x25", 3, 10, false),
new Part("TUBE-26x2", 1, 6, true),
new Part("CHAIN-11", 2, 4, false),
new Part("PAD-ROAD", 14, 6, false));
Predicate<Part> low = p -> p.quantity() < p.reorderAt();
Predicate<Part> discontinued = p -> p.discontinued();
Predicate<Part> rule = p -> true; // change this line
for (Part p : parts) {
if (rule.test(p)) System.out.println(p.code());
}
}
}Try it yourself
Your own functional interface
Declare a functional interface PriceRule with one method long apply(long cents), mark it @FunctionalInterface, and use lambdas to make two rules: member takes 10 off every hundred cents (so 1000 becomes 900) and round rounds down to a multiple of 25 cents.
Apply member and then round to 1999 cents. The program should print Member price: 1799 and Rounded: 1775.
public class Main {
// declare PriceRule here
public static void main(String[] args) {
long price = 1999;
System.out.println("Member price: " + price);
System.out.println("Rounded: " + price);
}
}Common mistakes
MistakeWriting a new loop method for every rule.
InsteadWrite one method that takes a Predicate and pass each rule as a lambda.
MistakeChanging a local variable after a lambda has used it.
InsteadKeep captured local variables effectively final, or compute the value before the lambda.
MistakeWriting a ten-line lambda.
InsteadMove long bodies into a named method and refer to it.
MistakePutting side effects such as counters inside predicates.
InsteadKeep predicates pure; the library decides how often to call them.
MistakeWriting a custom interface for every lambda.
InsteadUse the standard interfaces in java.util.function unless a name adds real meaning.
Summary and key terms
- A lambda expression is a short piece of behavior that can be passed, stored and returned like a value.
- It has parameters, an arrow and either an expression or a block body, and the compiler infers parameter types from its target.
- The target must be a functional interface, an interface with exactly one abstract method; @FunctionalInterface asks the compiler to check this. java.util.function supplies the common ones: Predicate, Function, Consumer, Supplier, UnaryOperator and BinaryOperator, plus two-argument and primitive versions.
- Default methods such as and, or, negate, andThen and compose combine small lambdas into larger rules.
- A lambda may use local variables only if they are effectively final, and this inside a lambda means the enclosing object.
- Long lambdas, lambdas with side effects and lambdas that must throw checked exceptions are signs that a named method would be clearer.
- Lambda expression
- A short block of code with parameters and a body that can be passed and stored like a value.
- Functional interface
- An interface with exactly one abstract method, which a lambda can implement.
- @FunctionalInterface
- An annotation that makes the compiler check that an interface has one abstract method.
- Predicate
- A functional interface whose method test takes a value and returns a boolean.
- Function
- A functional interface whose method apply turns a value of one type into another.
- Consumer
- A functional interface whose method accept takes a value and returns nothing.
- Supplier
- A functional interface whose method get takes nothing and returns a value.
- Effectively final
- A local variable that is never assigned again after its first value, so a lambda may use it.
- Target type
- The functional interface a lambda is assigned or passed to, from which its types are inferred.
Practice problems
Work each problem on paper first, then reveal the answer to check.
What makes an interface functional?
Show answer
It has exactly one abstract method.
Which standard interface turns a Part into a String?
Show answer
Function<Part, String>.
Why does a lambda that uses a local variable fail to compile after that variable is changed?
Show answer
Captured local variables must be effectively final.
How do you combine two Predicates so both must be true?
Show answer
first.and(second).
When should a lambda become a named method?
Show answer
When its body grows past a few lines or it needs a name in tests and stack traces.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.