Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 201 ยท Generics and Functional Programming

Functional Interfaces

Learn Java functional interfaces - Function, Predicate, Consumer, Supplier, BiFunction, operators, primitive versions, composing with andThen and negate, and @FunctionalInterface.

In Lambda Expressions you saw that a lambda needs a target type: an interface with exactly one abstract method. Such an interface is called a functional interface. You could invent a new one for every situation (PriceRule, EmailFilter, ReportPrinter), but most of the time you don't need to: the package java.util.function provides 43 ready-made interfaces covering almost every shape a function can have.

Knowing them pays off quickly. They're the vocabulary of streams, Optional, Map.computeIfAbsent, CompletableFuture and countless library APIs. This lesson covers the four core interfaces, their two-argument and operator variants, the primitive specializations that avoid boxing, the default methods that let you compose small functions into bigger ones, and how to write your own functional interface when the standard ones don't fit.

What makes an interface functional

A functional interface has exactly one abstract method. It may also have any number of default and static methods, and it may redeclare public Object methods like equals without them counting. Comparator is a good example: it declares compare and equals (from Object), plus dozens of default and static helpers, and it's still functional.

Java
@FunctionalInterface
interface Validator {
    boolean isValid(String input);              // the single abstract method

    default Validator and(Validator other) {    // default methods are fine
        return s -> isValid(s) && other.isValid(s);
    }
}

The @FunctionalInterface annotation is optional. It asks the compiler to verify the rule, so if someone later adds a second abstract method, they get a compile error instead of silently breaking every lambda that used the interface. Put it on every functional interface you write.

Many older JDK interfaces are functional too, even if they predate Java 8: Runnable (run()), Callable<V> (call()), Comparator<T> (compare), AutoCloseable (close()) and the listeners used in Swing.

The four core interfaces

Almost everything in java.util.function is a variation on four shapes:

Interface Method Takes โ†’ returns Typical use
Function<T, R> R apply(T t) one value โ†’ a result transform: order to total, string to length
Predicate<T> boolean test(T t) one value โ†’ boolean filter, validate, match
Consumer<T> void accept(T t) one value โ†’ nothing print, save, send: side effects
Supplier<T> T get() nothing โ†’ a value create lazily, provide defaults
Java Function, Predicate, Consumer and Supplier

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

transform doesn't know anything about orders: the caller decides what to keep (Predicate) and how to convert it (Function). That's the power of these interfaces: generic methods take the variable parts of an algorithm as parameters.

A Supplier is about when a value is created. Code that takes a supplier can call it only if it actually needs the value, which is why Optional.orElseGet(supplier) and Map.computeIfAbsent(key, function) take functions instead of ready-made values. (Method References explains the ArrayList::new syntax.)

Two arguments and operators

Each core shape has a two-argument version, and Function has two special cases where the input and output types are the same:

Interface Method Shape
BiFunction<T, U, R> R apply(T t, U u) two values โ†’ a result
BiPredicate<T, U> boolean test(T t, U u) two values โ†’ boolean
BiConsumer<T, U> void accept(T t, U u) two values โ†’ nothing
UnaryOperator<T> T apply(T t) extends Function<T, T>
BinaryOperator<T> T apply(T t1, T t2) extends BiFunction<T, T, T>

There's no BiSupplier, since a method can return only one value. UnaryOperator and BinaryOperator are just shorter names for common cases: List.replaceAll takes a UnaryOperator<E> and Stream.reduce takes a BinaryOperator<T>.

Java BiFunction, BiPredicate, BiConsumer and operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

BinaryOperator.minBy and maxBy turn a Comparator into an operator that picks the smaller or larger of two values, which is handy with reduce and collectors.

Primitive specializations

Generic interfaces work with objects, so Function<Integer, Integer> boxes every int into an Integer and unboxes it again. In tight loops over millions of numbers that costs time and memory. The JDK therefore includes versions for int, long and double (and one for boolean), with method names that say what they return:

Shape int versions Method
int โ†’ R IntFunction<R> R apply(int value)
T โ†’ int ToIntFunction<T>, ToIntBiFunction<T, U> int applyAsInt(T t)
int โ†’ int IntUnaryOperator int applyAsInt(int operand)
int, int โ†’ int IntBinaryOperator int applyAsInt(int left, int right)
int โ†’ boolean IntPredicate boolean test(int value)
int โ†’ nothing IntConsumer, ObjIntConsumer<T> void accept(int value), void accept(T t, int value)
nothing โ†’ int IntSupplier int getAsInt()
int โ†’ long / double IntToLongFunction, IntToDoubleFunction applyAsLong, applyAsDouble

The same pattern exists for Long... and Double... (LongPredicate, DoubleUnaryOperator, ToDoubleFunction, LongToIntFunction, and so on), plus BooleanSupplier. You'll mostly meet them through primitive streams: IntStream.filter takes an IntPredicate, and mapToInt takes a ToIntFunction.

Java Primitive functional interfaces avoid boxing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The timing line varies between runs, and the JIT can sometimes optimize boxing away, so don't read too much into small differences. The rule of thumb still holds: for number-crunching, pick the primitive interface, and for ordinary object code, the generic ones are fine. (Timing tips are in Choosing the Right Collection.)

Composing functions

The standard interfaces have default methods that combine functions into new ones, so you can build complex behavior from small, testable pieces:

Interface Methods
Function f.andThen(g) (f first, then g), f.compose(g) (g first, then f), Function.identity()
Predicate p.and(q), p.or(q), p.negate(), Predicate.not(p) (Java 11), Predicate.isEqual(x)
Consumer c.andThen(d) (run both, in order)
BiFunction f.andThen(g) (apply g to the result)
UnaryOperator UnaryOperator.identity()
Java andThen, compose, and, or, negate and not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read andThen as "do this, and then that" and compose as the mathematical f(g(x)): the argument function runs first. The two calls on plus2 give 9 and 5, which is the easiest way to remember the difference.

Predicate.not(...) exists mainly so you can negate a method reference: String::isBlank has no .negate() until it has a type, but Predicate.not(String::isBlank) gives it one.

Writing your own functional interface

Reach for a custom interface when:

  • No standard shape fits, for example a function of three arguments (there's no TriFunction in the JDK).
  • A descriptive name helps readers. PriceRule or RetryPolicy tells more than Function<Order, BigDecimal>, and it lets you add domain-specific default methods.
  • The function must throw a checked exception. The standard interfaces don't declare throws, as you saw in Lambda Expressions.
Java Custom functional interfaces, including one that throws

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

ThrowingFunction.unchecked adapts a function that throws checked exceptions into a normal Function, wrapping the checked exception in a RuntimeException so it can travel through APIs like streams. Libraries such as Vavr ship similar helpers; writing your own takes ten lines.

Lambdas convert to any functional interface with a compatible method, but two different interfaces are never interchangeable, even with the same shape. A Predicate<String> variable can't be passed where your Validator is expected. Adapt it with a method reference: validatorMethod(predicate::test).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which interface fits a lambda that takes an order and returns nothing, such as saving it to a database?

    A Consumer takes a value and returns nothing (void accept). It's the shape for side effects.
  2. 2. What does this print? Function<Integer, Integer> f = x -> x + 1; Function<Integer, Integer> g = x -> x * 10; IO.println(f.compose(g).apply(2));

    f.compose(g) runs g first and then f, so 2 * 10 = 20 and then 20 + 1 = 21. f.andThen(g) would give 30.
  3. 3. An interface has one abstract method, two default methods and one static method. Is it a functional interface?

    A functional interface has exactly one abstract method. Default and static methods don't count, and the annotation is optional (it only asks the compiler to check).
  4. 4. Why choose IntPredicate over Predicate<Integer> for filtering millions of numbers?

    The primitive specializations accept and return primitives directly, so no Integer objects are created and unboxed for each test.
  5. 5. Which expression keeps only non-blank strings in a stream?

    A method reference has no type of its own, so you can't call negate on it directly or use the ! operator. Predicate.not gives it the Predicate type and negates it.

Summary

  • A functional interface has exactly one abstract method; default, static and Object methods don't count. Mark yours with @FunctionalInterface.
  • The core four: Function<T, R> (transform), Predicate<T> (test), Consumer<T> (act), Supplier<T> (provide).
  • Two-argument versions are BiFunction, BiPredicate and BiConsumer; UnaryOperator<T> and BinaryOperator<T> are functions whose types all match.
  • Primitive specializations (IntPredicate, ToIntFunction, IntUnaryOperator, DoubleSupplier, ...) avoid boxing; their methods are named applyAsInt, getAsDouble and so on.
  • Compose with andThen, compose, identity, and, or, negate, Predicate.not and Consumer.andThen.
  • Write a custom interface for extra arities, descriptive domain names or checked exceptions.

Next: Method References, the even shorter syntax behind String::length, IO::println and ArrayList::new.