Lambda Expressions
sort, a condition to removeIf, a pipeline step to a stream. This lesson covers functional interfaces, lambda syntax, variable capture, the standard java.util.function interfaces, method references, and lambdas in comparators and streams.
Functional Interfaces
Java has no separate function type. A lambda is always an implementation of a functional interface: an interface with exactly one abstract method. The lambda's parameters and body become that method's implementation, and its types are inferred from the interface it is assigned to, its target type (see Type Inference). Marking such an interface @FunctionalInterface makes the compiler enforce the single-method rule.
// A lambda is an implementation of a functional interface's single abstract method.
@FunctionalInterface
interface Operation {
int apply(int a, int b);
}
class LambdaBasics {
static int calculate(int a, int b, Operation op) { return op.apply(a, b); }
public static void main(String[] args) {
Operation add = (a, b) -> a + b; // expression body
Operation max = (a, b) -> { // block body needs return
if (a > b) return a;
return b;
};
System.out.println(calculate(6, 3, add));
System.out.println(calculate(6, 3, max));
System.out.println(calculate(6, 3, (a, b) -> a * b)); // inline lambda
int offset = 100; // captured: must be effectively final
Operation shifted = (a, b) -> a + b + offset;
System.out.println(shifted.apply(1, 2));
// offset++; // error: would break the capture
}
}
Output:
9
6
18
103
Syntax Forms
| Form | Example |
|---|---|
| No parameters | () -> System.out.println("hi") |
| One parameter (parentheses optional) | s -> s.length() |
| Several parameters | (a, b) -> a + b |
Explicit or var types | (int a, int b) -> a + b, (var a, var b) -> a + b |
| Block body | (a, b) -> { int s = a + b; return s; } |
An expression body returns its value automatically; a block body needs an explicit return unless the method is void.
Capturing Variables
A lambda can read local variables from the enclosing method, but only if they are effectively final — never assigned after initialization, as offset is in the example. The lambda captures the value, so allowing later changes would make its behavior surprising, especially when it runs on another thread. Fields have no such restriction, which is one reason shared mutable fields inside lambdas cause concurrency bugs. Inside a lambda, this refers to the enclosing object, unlike in an anonymous class.
Standard Functional Interfaces
You rarely need to declare your own interface: java.util.function provides the common shapes.
| Interface | Method | Shape |
|---|---|---|
Function<T, R> | R apply(T) | transform a value |
BiFunction<T, U, R> | R apply(T, U) | combine two values |
UnaryOperator<T> / BinaryOperator<T> | T apply(T) / T apply(T, T) | same type in and out |
Predicate<T> | boolean test(T) | a condition |
Supplier<T> | T get() | produce a value on demand |
Consumer<T> | void accept(T) | use a value for its side effect |
Primitive specializations such as IntPredicate and ToIntFunction avoid boxing in performance-sensitive code. Many interfaces have default methods to combine them: andThen, compose, negate, and, or.
Method References
When a lambda only calls an existing method, a method reference names that method directly. There are four kinds: a static method (Math::max), an instance method of a particular object (System.out::println), an instance method of an arbitrary object of a type (String::length, where the object is the first argument), and a constructor (ArrayList::new).
// java.util.function interfaces and the four kinds of method reference.
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
class StandardFunctions {
public static void main(String[] args) {
Function<String, Integer> length = String::length; // instance method of any String
Predicate<String> isEmpty = String::isEmpty;
UnaryOperator<String> shout = s -> s.toUpperCase() + "!";
BiFunction<Integer, Integer, Integer> power = (b, e) -> (int) Math.pow(b, e);
Supplier<List<String>> fresh = java.util.ArrayList::new; // constructor reference
Consumer<Object> print = System.out::println; // method of a specific object
print.accept(length.apply("lambda"));
print.accept(isEmpty.negate().test("x"));
print.accept(shout.andThen(s -> "[" + s + "]").apply("hi"));
print.accept(power.apply(2, 10));
List<String> list = fresh.get();
list.add("new list");
print.accept(list);
Function<Integer, Integer> twice = x -> x * 2;
Function<Integer, Integer> plusOne = x -> x + 1;
print.accept(twice.andThen(plusOne).apply(5)); // (5 * 2) + 1 = 11
print.accept(twice.compose(plusOne).apply(5)); // (5 + 1) * 2 = 12
BiFunction<Integer, Integer, Integer> larger = Math::max; // static method reference
print.accept(larger.apply(3, 7));
}
}
Output:
6
true
[HI!]
1024
[new list]
11
12
7
Lambdas in Practice
Comparators and Streams
Most lambdas you write will be arguments to library methods: Comparator factories, Collection.removeIf, Map.computeIfAbsent, and above all the Stream API. A stream pipeline takes a source, applies intermediate operations such as filter, map and sorted, and ends with a terminal operation such as toList, sum or collect.
// Lambdas in practice: comparators and stream pipelines.
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
record Employee(String name, String team, int salary) {}
class LambdaStreams {
public static void main(String[] args) {
List<Employee> staff = List.of(
new Employee("Ana", "dev", 5200),
new Employee("Bo", "ops", 4100),
new Employee("Cy", "dev", 6100),
new Employee("Di", "ops", 4800));
List<String> byPay = staff.stream()
.sorted(Comparator.comparingInt(Employee::salary).reversed())
.map(Employee::name)
.toList();
System.out.println(byPay);
int devTotal = staff.stream()
.filter(e -> e.team().equals("dev"))
.mapToInt(Employee::salary)
.sum();
System.out.println("dev payroll: " + devTotal);
Map<String, Double> avgByTeam = staff.stream()
.collect(Collectors.groupingBy(Employee::team, java.util.TreeMap::new,
Collectors.averagingInt(Employee::salary)));
System.out.println(avgByTeam);
}
}
Output:
[Cy, Ana, Di, Bo]
dev payroll: 11300
{dev=5650.0, ops=4450.0}
Keep Lambdas Short
Keep lambdas short. When a lambda grows beyond two or three lines, move the body into a named method and pass a method reference: the name documents the intent, and the method can be tested on its own. Streams are evaluated lazily and only when the terminal operation runs; avoid side effects in intermediate steps. The Performance lesson covers parallel streams.
Practice
Exercises
- Sort a list of strings by length and then alphabetically, using
Comparator.comparingInt(String::length).thenComparing(...). - Write a method
static Predicate<Integer> between(int lo, int hi)that returns a lambda, and combine two of them withor. - Rewrite the
dev payrollcalculation with a classic loop and compare readability; then find the highest-paid employee per team withCollectors.groupingByandCollectors.maxBy.