Essay
Learning Java, Part 14: Lambda Expressions and Method References
Study notes on functional interfaces, expression and block lambdas, generic functional interfaces, passing lambdas as arguments, variable capture, exceptions in lambdas, method and constructor references, the predefined interfaces in java.util.function, and a first look at streams. Written entirely by an AI model.
Python has always let you pass a function as a value: sorted(names, key=len). Java added the equivalent in Java 8 with lambda expressions. They replaced most anonymous classes, and the collections and streams libraries are designed around them.
Functional interfaces
A lambda is not a free-standing function. It is a short way to implement a functional interface: an interface with exactly one abstract method. Runnable (run()) and Comparator<T> (compare(a, b)) are functional interfaces, and you can write your own:
@FunctionalInterface
interface Pricing {
double apply(double price);
}
public class Lambdas {
public static void main(String[] args) {
Pricing discount = p -> p * 0.9; // expression lambda
Pricing withTax = p -> { // block lambda
double tax = p * 0.1;
return p + tax;
};
System.out.println(discount.apply(10));
System.out.println(withTax.apply(10));
}
}
9.0
11.0
- The lambda’s parameters and return value must match the interface’s single method. The compiler infers the parameter types from the target.
- Expression form,
p -> p * 0.9, returns the expression’s value. Block form, with braces, needs an explicitreturnif the method returns a value. - Zero parameters:
() -> 42. Several:(a, b) -> a + b. Types can be written out:(double p) -> p * 2. @FunctionalInterfaceis optional; it makes the compiler check that there is exactly one abstract method. Default and static methods don’t count.
Generic functional interfaces and lambdas as arguments
A functional interface can be generic, so one interface serves many types. Passing behaviour into a method is the main use:
interface Test<T> {
boolean check(T value);
}
public class Filtering {
static <T> int countWhere(T[] items, Test<T> test) {
int n = 0;
for (T x : items) if (test.check(x)) n++;
return n;
}
public static void main(String[] args) {
Integer[] marks = {45, 72, 88, 51, 30};
String[] teas = {"green", "oolong", "earl grey"};
System.out.println(countWhere(marks, m -> m >= 50));
System.out.println(countWhere(teas, t -> t.contains(" ")));
}
}
3
1
Before Java 8, each of those would have been an anonymous inner class with five lines of ceremony. Compare:
Test<Integer> pass = new Test<Integer>() {
@Override public boolean check(Integer m) { return m >= 50; }
};
Test<Integer> pass2 = m -> m >= 50; // the same thing
Variable capture
A lambda can use local variables from the surrounding method, but only if they are effectively final: never reassigned after they are set. It can read and change fields freely.
import java.util.function.Supplier;
public class Capture {
public static void main(String[] args) {
String greeting = "Hi"; // never reassigned
Supplier<String> s = () -> greeting + "!";
System.out.println(s.get());
int count = 0;
// Runnable r = () -> count++; // compile error: count is not effectively final
}
}
Hi!
Inside a lambda, this means the enclosing object, unlike an anonymous class, where this is the anonymous object.
Exceptions in lambdas
A lambda may throw an unchecked exception freely. It may throw a checked exception only if the functional interface’s method declares it. The standard interfaces in java.util.function declare none, which is why calling a method that throws IOException inside a lambda passed to a stream needs a try/catch within the lambda.
Method references
When a lambda just calls an existing method, a method reference says the same thing more briefly, using :::
| Kind | Reference | Equivalent lambda |
|---|---|---|
| static method | Integer::parseInt |
s -> Integer.parseInt(s) |
| method of a particular object | System.out::println |
x -> System.out.println(x) |
| method of any object of a type | String::length |
s -> s.length() |
| constructor | ArrayList::new |
() -> new ArrayList<>() |
import java.util.*;
import java.util.function.*;
public class Refs {
public static void main(String[] args) {
Function<String, Integer> parse = Integer::parseInt;
System.out.println(parse.apply("12") + 1);
List<String> teas = new ArrayList<>(List.of("oolong", "chai", "sencha"));
teas.sort(Comparator.comparing(String::length));
teas.forEach(System.out::println);
Supplier<List<String>> fresh = ArrayList::new;
List<String> empty = fresh.get();
System.out.println(empty.isEmpty());
}
}
13
chai
oolong
sencha
true
sort is stable, so oolong and sencha keep their original order.
The predefined functional interfaces
java.util.function has ready-made interfaces, so you rarely need to write your own:
| Interface | Method | Takes | Returns | Example |
|---|---|---|---|---|
Predicate<T> |
test |
T |
boolean |
s -> s.isEmpty() |
Function<T,R> |
apply |
T |
R |
s -> s.length() |
Consumer<T> |
accept |
T |
nothing | System.out::println |
Supplier<T> |
get |
nothing | T |
() -> new Random() |
UnaryOperator<T> |
apply |
T |
T |
s -> s.trim() |
BinaryOperator<T> |
apply |
T, T |
T |
Integer::sum |
There are also primitive versions such as IntPredicate and ToIntFunction<T> that avoid boxing, and two-argument versions such as BiFunction<T,U,R>. Many have default methods for combining them: Predicate.and, negate, Function.andThen, Comparator.thenComparing.
A first look at streams
The book stops before streams, but they are where lambdas pay off and they appear in most modern Java. A stream is a pipeline over a collection’s elements: a source, zero or more intermediate operations (lazy, returning a new stream) and one terminal operation (which produces the result).
import java.util.*;
import java.util.stream.*;
public class Streams {
record Order(String tea, int cups, double price) {}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("chai", 2, 4.5), new Order("green", 1, 3.0),
new Order("chai", 3, 4.5), new Order("oolong", 1, 4.2));
double revenue = orders.stream()
.mapToDouble(o -> o.cups() * o.price())
.sum();
System.out.println(revenue);
List<String> bigOrders = orders.stream()
.filter(o -> o.cups() >= 2)
.map(Order::tea)
.distinct()
.collect(Collectors.toList());
System.out.println(bigOrders);
Map<String, Integer> cupsByTea = orders.stream()
.collect(Collectors.groupingBy(Order::tea, TreeMap::new,
Collectors.summingInt(Order::cups)));
System.out.println(cupsByTea);
System.out.println(IntStream.rangeClosed(1, 5).map(x -> x * x).boxed().toList());
}
}
29.7
[chai]
{chai=5, green=1, oolong=1}
[1, 4, 9, 16, 25]
filter, map, sorted and distinct are intermediate; collect, sum, count, forEach and toList are terminal. A stream can be used only once, and it never changes its source. It is the Java counterpart of Python’s comprehensions and sum(...) over a generator.
Exam-style checks
- What is a functional interface? Is
Comparatorone, given that it has many methods? - Rewrite an anonymous
Comparatorclass as a lambda and then as a method reference. - Why can a lambda not change a local variable of the method that contains it?
- Which predefined interface would you use for a function that takes a
Stringand returns aboolean? - Write a stream pipeline that returns the names of students with marks of at least 80, sorted.
Where to practise
Schildt’s Chapter 14 passes string-processing lambdas to a method that applies them; write one for reversing, upper-casing and removing spaces. Then take the word-frequency program from Part 13 and rewrite it with streams and Collectors.groupingBy, and check that the two versions agree.