Functional interfaces in depth
A lambda is an object that implements an interface with a single abstract method. java.util.function has over forty such interfaces, but they follow a few patterns: general shapes like Function and Predicate, primitive versions that avoid boxing, and default methods that combine functions. This page shows how the JVM creates lambda objects, the four kinds of method reference and two traps they hide, composition, primitive specializations, checked exceptions, and custom interfaces.
Contents
What a functional interface is
A functional interface is an interface with exactly one abstract method; default and static methods do not count. Any lambda expression or method reference can be used where such an interface is expected, and the compiler checks that its parameters and return type match that one method. The @FunctionalInterface
Lambdas arrived in Java 8 (JSR 335), together with the java.util.functioninvokedynamicLambdaMetafactory.metafactory
| Interface | Method | Shape | Best for |
|---|---|---|---|
Function<T, R>BiFunction<T, U, R> | apply | Arguments in, result out | Transformations, map |
UnaryOperator<T>BinaryOperator<T> | apply | Same type in and out | replaceAllreduce |
Predicate<T>BiPredicate<T, U> | test | Arguments in, boolean | filterremoveIf |
Consumer<T>BiConsumer<T, U> | accept | Arguments in, nothing out | forEach |
Supplier<T> | get | Nothing in, result out | Lazy values, factories |
IntFunctionToIntFunctionIntUnaryOperatorObjIntConsumer | applyAsInt | Primitive intlongdouble | Numeric code without boxing |
The package has 43 interfaces in all, and older interfaces such as RunnableCallableComparator
What a lambda object is
The program inspects the class of a lambda, compares lambdas created twice, and contrasts thisthis
import java.util.function.IntSupplier;
import java.util.function.Supplier;
public class LambdaInternals {
private final String name = "outer instance";
static Supplier<String> nonCapturing() {
return () -> "constant"; // uses nothing from its surroundings
}
static IntSupplier capturing(int base) {
return () -> base + 1; // captures the local variable 'base'
}
void showThis() {
Runnable lambda = () -> System.out.println("this in lambda: " + this.name);
Runnable anon = new Runnable() {
@Override
public void run() {
System.out.println("this in anonymous class: " + this.getClass().getName());
}
};
lambda.run();
anon.run();
}
public static void main(String[] args) {
Supplier<String> s = nonCapturing();
Class<?> c = s.getClass();
System.out.println("lambda class is hidden: " + c.isHidden());
System.out.println("its name contains $$Lambda: " + c.getName().contains("$$Lambda"));
System.out.println("implements Supplier: " + (s instanceof Supplier));
System.out.println("synthetic: " + c.isSynthetic());
// HotSpot reuses one instance for a non-capturing lambda (not guaranteed by the JLS)
System.out.println("non-capturing, same object each time: "
+ (nonCapturing() == nonCapturing()));
System.out.println("capturing, same object each time: "
+ (capturing(1) == capturing(1)));
System.out.println("captured value used: " + capturing(41).getAsInt());
new LambdaInternals().showThis();
}
}
Output:
lambda class is hidden: true
its name contains $$Lambda: true
implements Supplier: true
synthetic: true
non-capturing, same object each time: true
capturing, same object each time: false
captured value used: 42
this in lambda: outer instance
this in anonymous class: LambdaInternals$1
- The lambda's class is hidden and synthetic, and its name contains
; it implements$$Lambda like any hand-written class would.Supplier - A lambda that captures nothing was the same object both times: HotSpot creates it once and returns that instance on every evaluation. A capturing lambda needs a new object each time to hold the captured value, here
. The language specification allows either behaviour, so never compare lambdas withbase or use them as map keys.== - Captured local variables must be effectively final. The value is copied into the lambda object when it is created, which is why a later change to the variable could not be seen and the compiler forbids it.
- Inside the lambda,
is the enclosingthis object. Inside the anonymous class,LambdaInternals is the anonymous object itself, of classthis . A lambda introduces no new scope for names, which also means it cannot declare a local variable that shadows one from the enclosing method.LambdaInternals$1
The four kinds of method reference, and two traps
A method reference is a shorter way to write a lambda that only calls one method. There are four kinds, and the comments in the program give the equivalent lambda for each. The second half shows that one kind, the bound reference, is not quite equivalent.
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
public class MethodRefs {
record Point(int x, int y) { }
public static void main(String[] args) {
// 1. Static method: Integer::parseInt is s -> Integer.parseInt(s)
Function<String, Integer> parse = Integer::parseInt;
// 2. Bound instance method: prefix::concat is s -> prefix.concat(s)
String prefix = "id-";
Function<String, String> tag = prefix::concat;
// 3. Unbound instance method: String::length is s -> s.length()
Function<String, Integer> len = String::length;
BiFunction<String, String, Boolean> starts = String::startsWith;
// 4. Constructor: Point::new is (x, y) -> new Point(x, y)
BiFunction<Integer, Integer, Point> make = Point::new;
Supplier<List<String>> newList = ArrayList::new;
System.out.println("1. parse(\"42\") + 1 = " + (parse.apply("42") + 1));
System.out.println("2. tag(\"7\") = " + tag.apply("7"));
System.out.println("3. len(\"lambda\") = " + len.apply("lambda")
+ ", starts(\"lambda\", \"lam\") = " + starts.apply("lambda", "lam"));
System.out.println("4. make(3, 4) = " + make.apply(3, 4)
+ ", newList is empty: " + newList.get().isEmpty());
// Trap A: a bound receiver is evaluated once, when the reference is created
StringBuilder current = new StringBuilder("first");
Supplier<String> viaRef = current::toString;
Supplier<String> viaLambda = () -> current.toString();
current.setLength(0);
current.append("changed");
System.out.println("A. same object mutated: ref " + viaRef.get()
+ ", lambda " + viaLambda.get());
Holder h = new Holder();
Supplier<String> boundToOld = h.text::trim; // h.text is read NOW
Supplier<String> readsLater = () -> h.text.trim();
h.text = " new ";
System.out.println("A. field reassigned: ref [" + boundToOld.get()
+ "], lambda [" + readsLater.get() + "]");
// Trap B: a null receiver fails when the reference is created, not when it is called
String missing = null;
try {
Supplier<Integer> lazy = () -> missing.length(); // fine until called
System.out.println("B. lambda with null created fine: " + (lazy != null));
Supplier<Integer> eager = missing::length; // throws right here
System.out.println("never printed " + eager);
} catch (NullPointerException e) {
System.out.println("B. method reference on null: NullPointerException at creation");
}
}
static class Holder {
String text = " old ";
}
}
Output:
1. parse("42") + 1 = 43
2. tag("7") = id-7
3. len("lambda") = 6, starts("lambda", "lam") = true
4. make(3, 4) = Point[x=3, y=4], newList is empty: true
A. same object mutated: ref changed, lambda changed
A. field reassigned: ref [old], lambda [new]
B. lambda with null created fine: true
B. method reference on null: NullPointerException at creation
- Static (
), bound (Integer::parseInt ), unbound (prefix::concat , where the first argument becomes the receiver) and constructor (String::length ,Point::new ) references all produced the expected results.ArrayList::new as aString::startsWith shows that an unbound reference takes the receiver as its first parameter.BiFunction - Trap A: in
, the expressionh.text::trim is evaluated when the reference is created. After the field was reassigned, the reference still trimmed the old string, "old", while the lambda read the field at call time and gave "new". When the receiver is the same mutable object, as with theh.text , both see the change.StringBuilder - Trap B: for the same reason, a bound reference on a
receiver throwsnull immediately, at creation, while the equivalent lambda fails only when called. This is specified behaviour (JLS 15.13.3), and it can move a stack trace far from where you expect it.NullPointerException
Composing functions
The default methods on the standard interfaces combine small functions into new ones without writing new lambdas. The example values are chosen so that the order of composition visibly changes the result.
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
public class Composition {
public static void main(String[] args) {
Function<Integer, Integer> plus2 = x -> x + 2;
Function<Integer, Integer> times3 = x -> x * 3;
// andThen: this first, then the argument. compose: the argument first.
System.out.println("plus2.andThen(times3)(5) = " + plus2.andThen(times3).apply(5));
System.out.println("plus2.compose(times3)(5) = " + plus2.compose(times3).apply(5));
System.out.println("Function.identity().apply(\"x\") = " + Function.identity().apply("x"));
// A text-cleaning pipeline built from small steps
UnaryOperator<String> trim = String::strip;
UnaryOperator<String> lower = String::toLowerCase;
Function<String, String> collapse = s -> s.replaceAll("\\s+", " ");
Function<String, String> clean = trim.andThen(lower).andThen(collapse);
System.out.println("clean: [" + clean.apply(" Hello WORLD ") + "]");
// Predicates combine with and / or / negate
Predicate<String> notBlank = s -> !s.isBlank();
Predicate<String> shortWord = s -> s.length() <= 5;
Predicate<String> valid = notBlank.and(shortWord);
for (String s : new String[] {"ok", " ", "toolong"}) {
System.out.println("valid(\"" + s + "\") = " + valid.test(s)
+ ", invalid = " + valid.negate().test(s));
}
// BinaryOperator helpers
BinaryOperator<Integer> larger = BinaryOperator.maxBy(Integer::compare);
System.out.println("maxBy(4, 9) = " + larger.apply(4, 9));
// BiFunction.andThen
BiFunction<Integer, Integer, Integer> area = (w, h) -> w * h;
System.out.println("area then describe: " + area.andThen(a -> a + " m2").apply(3, 4));
}
}
Output:
plus2.andThen(times3)(5) = 21
plus2.compose(times3)(5) = 17
Function.identity().apply("x") = x
clean: [hello world]
valid("ok") = true, invalid = false
valid(" ") = false, invalid = true
valid("toolong") = false, invalid = true
maxBy(4, 9) = 9
area then describe: 12 m2
appliesplus2.andThen(times3) first: (5 + 2) × 3 = 21.plus2 applies the argument first: 5 × 3 + 2 = 17.plus2.compose(times3) reads in execution order, so it is usually clearer.andThen- The cleaning pipeline chains three steps into one
that can be stored, passed around and applied many times.Function ,Predicate.and andor build compound conditions;negate andand short-circuit likeor and&& . Java 11 added the static|| , convenient with method references:Predicate.not .filter(Predicate.not(String::isBlank)) andBinaryOperator.maxBy build operators from aminBy , andComparator post-processes a two-argument result.BiFunction.andThen
Primitive specializations and boxing
Generic interfaces work only with objects, so a Function<Integer, Integer>intIntegerInteger
import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.IntPredicate;
import java.util.function.IntUnaryOperator;
import java.util.function.ToIntFunction;
public class Primitives {
public static void main(String[] args) {
// Boxed versions allocate Integer objects; primitive versions do not
Function<Integer, Integer> boxedSquare = x -> x * x;
IntUnaryOperator square = x -> x * x;
int n = 20000000;
long boxedBest = Long.MAX_VALUE;
long primBest = Long.MAX_VALUE;
long a = 0;
long b = 0;
for (int run = 0; run < 3; run++) { // best of 3 runs
long start = System.nanoTime();
a = 0;
for (int i = 0; i < n; i++) {
a += boxedSquare.apply(i % 1000 + 1000); // outside the Integer cache
}
boxedBest = Math.min(boxedBest, System.nanoTime() - start);
start = System.nanoTime();
b = 0;
for (int i = 0; i < n; i++) {
b += square.applyAsInt(i % 1000 + 1000);
}
primBest = Math.min(primBest, System.nanoTime() - start);
}
System.out.println("same total: " + (a == b));
System.out.printf("Function<Integer, Integer>: %,4d ms%n", boxedBest / 1000000);
System.out.printf("IntUnaryOperator: %,4d ms%n", primBest / 1000000);
IntPredicate even = x -> x % 2 == 0;
IntBinaryOperator gcd = (x, y) -> {
while (y != 0) {
int t = y;
y = x % y;
x = t;
}
return x;
};
ToIntFunction<String> length = String::length;
System.out.println("even(10) = " + even.test(10));
System.out.println("gcd(84, 36) = " + gcd.applyAsInt(84, 36));
System.out.println("length(\"lambda\") = " + length.applyAsInt("lambda"));
}
}
Output (rough timings from a 2-CPU Linux machine running JDK 21):
same total: true
Function<Integer, Integer>: 22 ms
IntUnaryOperator: 11 ms
even(10) = true
gcd(84, 36) = 12
length("lambda") = 6
- The boxed version was about twice as slow here. The gap is smaller than one might expect because, once the JIT inlines the lambda, escape analysis can remove many of the temporary
objects. When boxed values escape, for example into a collection, the cost of allocation and garbage collection grows.Integer - Primitive interfaces are named by pattern:
takes anIntPredicate ,int returns one,ToIntFunction<T> combines two, andIntBinaryOperator maps anIntFunction<R> to an object. There are versions forint ,int andlong only;double results useboolean , and the one primitive supplier of booleans isPredicate .BooleanSupplier ,IntStream andLongStream use these interfaces throughout, which is whyDoubleStream followed bymapToInt is faster thansum() withmap .reduce(0, Integer::sum)
Checked exceptions in lambdas
None of the standard interfaces declares a checked exception, so a lambda passed to mapIOException
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.function.Function;
public class CheckedExceptions {
// A method that throws a checked exception, like many I/O methods
static String load(String name) throws IOException {
if (name.startsWith("bad")) {
throw new IOException("cannot read " + name);
}
return name.toUpperCase();
}
// A functional interface that may throw, plus an adapter to the standard Function
@FunctionalInterface
interface ThrowingFunction<T, R, E extends Exception> {
R apply(T t) throws E;
static <T, R> Function<T, R> unchecked(ThrowingFunction<T, R, IOException> f) {
return t -> {
try {
return f.apply(t);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
}
}
public static void main(String[] args) {
List<String> names = List.of("a.txt", "b.txt", "bad.txt");
// Function.apply declares no checked exception, so this does not compile:
// names.stream().map(CheckedExceptions::load)
// 1. Wrap inside the lambda
try {
names.stream().map(n -> {
try {
return load(n);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}).forEach(s -> System.out.println("1. loaded " + s));
} catch (UncheckedIOException e) {
System.out.println("1. stopped: " + e.getCause().getMessage());
}
// 2. The same with a reusable adapter
try {
names.stream().map(ThrowingFunction.unchecked(CheckedExceptions::load))
.forEach(s -> System.out.println("2. loaded " + s));
} catch (UncheckedIOException e) {
System.out.println("2. stopped: " + e.getCause().getMessage());
}
// 3. Turn failures into values so one bad item does not stop the rest
names.stream()
.map(n -> {
try {
return "ok " + load(n);
} catch (IOException e) {
return "failed " + e.getMessage();
}
})
.forEach(s -> System.out.println("3. " + s));
}
}
Output:
1. loaded A.TXT
1. loaded B.TXT
1. stopped: cannot read bad.txt
2. loaded A.TXT
2. loaded B.TXT
2. stopped: cannot read bad.txt
3. ok A.TXT
3. ok B.TXT
3. failed cannot read bad.txt
- Catching inside the lambda and rethrowing as
lets the exception travel through the stream; the caller unwraps it withUncheckedIOException . The stream stopped at "bad.txt".getCause() - A small
interface with a static adapter does the same wrapping once, so call sites stay short:ThrowingFunction .map(unchecked(CheckedExceptions::load)) - Turning each failure into a value, here a string, lets the remaining items go on. In real code the value would be a result type, such as a record holding either the data or the error.
A functional interface may declare throwsCallable.call()ExceptionE extends Exception
Designing custom functional interfaces
When no standard interface fits, or when a domain name says more than Function<Double, Double>
import java.util.function.Function;
public class CustomInterfaces {
// Three arguments: no standard interface exists, so declare one
@FunctionalInterface
interface TriFunction<A, B, C, R> {
R apply(A a, B b, C c);
default <V> TriFunction<A, B, C, V> andThen(Function<? super R, ? extends V> after) {
return (a, b, c) -> after.apply(apply(a, b, c));
}
}
// A domain name makes intent clearer than a generic Function<Double, Double>
@FunctionalInterface
interface DiscountRule {
double apply(double price);
static DiscountRule percent(double p) {
return price -> price * (1 - p / 100);
}
default DiscountRule then(DiscountRule next) {
return price -> next.apply(apply(price));
}
}
public static void main(String[] args) {
TriFunction<Integer, Integer, Integer, Integer> volume = (l, w, h) -> l * w * h;
System.out.println("volume: " + volume.andThen(v -> v + " cm3").apply(2, 3, 4));
DiscountRule rule = DiscountRule.percent(10).then(p -> p - 5);
System.out.printf("100.00 after 10%% off then 5 off: %.2f%n", rule.apply(100));
// Currying: a function that returns a function
Function<Integer, Function<Integer, Integer>> adder = x -> y -> x + y;
Function<Integer, Integer> add10 = adder.apply(10);
System.out.println("add10(5) = " + add10.apply(5));
}
}
Output:
volume: 24 cm3
100.00 after 10% off then 5 off: 85.00
add10(5) = 15
fills a gap: the JDK stops at two arguments. Its defaultTriFunction mirrors the one onandThen , so it composes the same way: 2 × 3 × 4 = 24, then formatted.Function is aDiscountRule -to-double function with a name, a static factory and a combining method. 100 minus 10% is 90, minus 5 is 85.00. Signatures such asdouble document themselves in a wayapply(DiscountRule rule) cannot.DoubleUnaryOperator- Currying turns a two-argument function into a function that returns a function:
is a new function that adds 10. It works, but nestedadder.apply(10) types quickly get hard to read in Java.Function - Overloading a method on two functional interfaces with the same shape, for example one taking a
and one aSupplier<T> , makes some lambdas ambiguous and forces callers to cast. Prefer distinct method names.Callable<T>
Choosing an interface
| Need | Use |
|---|---|
| Transform a value | Function<T, R>UnaryOperator<T> |
| Test a value | Predicate<T> |
| Do something with a value | Consumer<T> |
| Produce a value lazily | Supplier<T> |
| Combine two values of one type | BinaryOperator<T> |
| Numbers in hot code | The IntLongDouble |
| A task that may throw checked exceptions | Callable<V>throws |
| Three or more arguments, or a domain concept | A custom @FunctionalInterface |
For the language side of lambdas, see invokedynamic