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 annotation is optional, but it makes the compiler reject the interface if someone later adds a second abstract method.

Lambdas arrived in Java 8 (JSR 335), together with the java.util.function package. A lambda is not compiled to an anonymous inner class. The compiler moves its body into a private method and emits an invokedynamic instruction. The first time that instruction runs, the bootstrap method LambdaMetafactory.metafactory generates a small class implementing the interface, and since Java 15 that class is a hidden class (JEP 371), invisible to class loaders and reflection by name. Later evaluations reuse the generated class, so a lambda costs little more than a method call.

The families in java.util.function
InterfaceMethodShapeBest for
Function<T, R>, BiFunction<T, U, R>applyArguments in, result outTransformations, map
UnaryOperator<T>, BinaryOperator<T>applySame type in and outreplaceAll, reduce
Predicate<T>, BiPredicate<T, U>testArguments in, boolean outfilter, removeIf
Consumer<T>, BiConsumer<T, U>acceptArguments in, nothing outforEach, callbacks
Supplier<T>getNothing in, result outLazy values, factories
IntFunction, ToIntFunction, IntUnaryOperator, ObjIntConsumer and othersapplyAsInt and similarPrimitive int, long or double versionsNumeric code without boxing

The package has 43 interfaces in all, and older interfaces such as Runnable, Callable and Comparator are functional interfaces too. The programs below ran on JDK 21.

What a lambda object is

The program inspects the class of a lambda, compares lambdas created twice, and contrasts this inside a lambda with this inside an anonymous class. The generated class name contains a number that changes between runs, so only its properties are printed.

Java
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:

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 $$Lambda; it implements Supplier like any hand-written class would.
  • 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 base. The language specification allows either behaviour, so never compare lambdas with == 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, this is the enclosing LambdaInternals object. Inside the anonymous class, this is the anonymous object itself, of class LambdaInternals$1. A lambda introduces no new scope for names, which also means it cannot declare a local variable that shadows one from the enclosing method.

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.

Java
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:

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 (Integer::parseInt), bound (prefix::concat), unbound (String::length, where the first argument becomes the receiver) and constructor (Point::new, ArrayList::new) references all produced the expected results. String::startsWith as a BiFunction shows that an unbound reference takes the receiver as its first parameter.
  • Trap A: in h.text::trim, the expression h.text 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 the StringBuilder, both see the change.
  • Trap B: for the same reason, a bound reference on a null receiver throws NullPointerException 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.

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.

Java
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:

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
  • plus2.andThen(times3) applies plus2 first: (5 + 2) × 3 = 21. plus2.compose(times3) applies the argument first: 5 × 3 + 2 = 17. andThen reads in execution order, so it is usually clearer.
  • The cleaning pipeline chains three steps into one Function that can be stored, passed around and applied many times.
  • Predicate.and, or and negate build compound conditions; and and or short-circuit like && and ||. Java 11 added the static Predicate.not, convenient with method references: filter(Predicate.not(String::isBlank)).
  • BinaryOperator.maxBy and minBy build operators from a Comparator, and BiFunction.andThen post-processes a two-argument result.

Primitive specializations and boxing

Generic interfaces work only with objects, so a Function<Integer, Integer> boxes every int argument and result into an Integer. The primitive versions avoid that. The program squares 20 million numbers both ways, using values from 1,000 to 1,999 so that the small Integer cache (-128 to 127) does not hide the boxing. Best of 3 runs, a rough comparison.

Java
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):

Output
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 Integer objects. When boxed values escape, for example into a collection, the cost of allocation and garbage collection grows.
  • Primitive interfaces are named by pattern: IntPredicate takes an int, ToIntFunction<T> returns one, IntBinaryOperator combines two, and IntFunction<R> maps an int to an object. There are versions for int, long and double only; boolean results use Predicate, and the one primitive supplier of booleans is BooleanSupplier.
  • IntStream, LongStream and DoubleStream use these interfaces throughout, which is why mapToInt followed by sum() is faster than map with reduce(0, Integer::sum).

Checked exceptions in lambdas

None of the standard interfaces declares a checked exception, so a lambda passed to map cannot let an IOException escape. The program loads three names, one of which fails, in three common ways.

Java
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:

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
  1. Catching inside the lambda and rethrowing as UncheckedIOException lets the exception travel through the stream; the caller unwraps it with getCause(). The stream stopped at "bad.txt".
  2. A small ThrowingFunction interface with a static adapter does the same wrapping once, so call sites stay short: map(unchecked(CheckedExceptions::load)).
  3. 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 throws, as Callable.call() does with Exception, and a generic exception parameter like E extends Exception lets callers name the exact type. Such interfaces cannot be passed to the stream API directly, which is why the adapter is needed.

Designing custom functional interfaces

When no standard interface fits, or when a domain name says more than Function<Double, Double>, declare your own. The program defines a three-argument function, a discount rule with factory and combining methods, and shows currying with the standard types.

Java
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:

Output
volume: 24 cm3
100.00 after 10% off then 5 off: 85.00
add10(5) = 15
  • TriFunction fills a gap: the JDK stops at two arguments. Its default andThen mirrors the one on Function, so it composes the same way: 2 × 3 × 4 = 24, then formatted.
  • DiscountRule is a double-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 as apply(DiscountRule rule) document themselves in a way DoubleUnaryOperator cannot.
  • Currying turns a two-argument function into a function that returns a function: adder.apply(10) is a new function that adds 10. It works, but nested Function types quickly get hard to read in Java.
  • Overloading a method on two functional interfaces with the same shape, for example one taking a Supplier<T> and one a Callable<T>, makes some lambdas ambiguous and forces callers to cast. Prefer distinct method names.

Choosing an interface

Which functional interface to use
NeedUse
Transform a valueFunction<T, R>, or UnaryOperator<T> for the same type
Test a valuePredicate<T>
Do something with a valueConsumer<T>
Produce a value lazilySupplier<T>
Combine two values of one typeBinaryOperator<T>
Numbers in hot codeThe Int, Long and Double specializations
A task that may throw checked exceptionsCallable<V>, or your own interface with throws
Three or more arguments, or a domain conceptA custom @FunctionalInterface

For the language side of lambdas, see lambdas; for using these interfaces in pipelines, see streams and advanced streams; for invokedynamic itself, see method handles.