00:00

Functional Interfaces in Java 8

Last updated: · Standard (Java 8)

A functional interface is an interface with exactly one abstract method. It is the type that a lambda expression or method reference becomes. Java 8 added the @FunctionalInterface annotation and the java.util.function package with ready-made interfaces such as Predicate and Function.

This tutorial shows the built-in interfaces you will use most, how to combine them, and how to design your own.

1. Why Are Functional Interfaces Needed?

Java does not have function types like (int) -> int. Instead, every lambda needs an interface to give it a type. Before Java 8, libraries had to invent their own single-method interfaces, so the same idea appeared under many names.

The java.util.function package standardises about 40 such interfaces. APIs like streams, Optional and CompletableFuture accept them, so the same lambda style works everywhere.

2. Rules and the @FunctionalInterface Annotation

PriceRule.java
@FunctionalInterface
interface PriceRule {
    double apply(double price);              // the single abstract method

    default PriceRule twice() {             // default methods are allowed
        return p -> apply(apply(p));
    }

    static PriceRule identity() {           // static methods are allowed
        return p -> p;
    }
}
  • Exactly one abstract method; any number of default and static methods.
  • Methods that match public methods of Object, such as equals, do not count. That is why Comparator is functional even though it declares equals.
  • @FunctionalInterface is optional, but it makes the compiler report an error if a second abstract method is added later.

3. The Core Built-in Interfaces

InterfaceMethodShapeTypical use
Predicate<T>test(T)T → booleanfiltering, validation
Function<T,R>apply(T)T → Rconverting values
Consumer<T>accept(T)T → voidprinting, saving
Supplier<T>get()() → Tlazy defaults, factories
UnaryOperator<T>apply(T)T → Ttransforming in place
BiFunction<T,U,R>apply(T, U)(T, U) → Rcombining two values

Primitive versions such as IntPredicate and ToIntFunction avoid boxing int values into Integer.

4. Practical Examples

Example 1: Using and combining built-in interfaces

BuiltInFunctions.java
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;

public class BuiltInFunctions {
    public static void main(String[] args) {
        Predicate<String> isEmail = s -> s.contains("@");                // T -> boolean
        Function<String, Integer> length = String::length;              // T -> R
        Consumer<String> printer = s -> System.out.println("  " + s);   // T -> void
        Supplier<String> defaultUser = () -> "guest";                    // () -> T
        UnaryOperator<String> upper = String::toUpperCase;              // T -> T
        BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;     // (T, U) -> R

        System.out.println("isEmail(\"asha@mail.com\") = " + isEmail.test("asha@mail.com"));
        System.out.println("length(\"invoice\")       = " + length.apply("invoice"));
        System.out.println("defaultUser.get()        = " + defaultUser.get());
        System.out.println("upper(\"rupee\")           = " + upper.apply("rupee"));
        System.out.println("add(40, 2)               = " + add.apply(40, 2));

        // Functions compose: andThen runs the second after the first
        Function<String, String> trimThenUpper = ((Function<String, String>) String::trim).andThen(upper);
        printer.accept(trimThenUpper.apply("   order shipped  "));

        // Predicates combine with and(), or() and negate()
        Predicate<String> validEmail = isEmail.and(s -> s.endsWith(".com"));
        printer.accept("ravi@site.org valid? " + validEmail.test("ravi@site.org"));
    }
}
Output
isEmail("asha@mail.com") = true
length("invoice")       = 7
defaultUser.get()        = guest
upper("rupee")           = RUPEE
add(40, 2)               = 42
  ORDER SHIPPED
  ravi@site.org valid? false

andThen chains two functions, and Predicate.and combines two conditions, so small rules can be built into larger ones without new classes.

Example 2: Writing a custom functional interface

When no built-in interface describes your domain clearly, define your own. A name like DiscountRule reads better than UnaryOperator<Double>.

CustomFunctionalInterface.java
public class CustomFunctionalInterface {

    // Exactly one abstract method; the annotation makes the compiler check it
    @FunctionalInterface
    interface DiscountRule {
        double apply(double price);

        // default and static methods do not count as abstract methods
        default DiscountRule then(DiscountRule next) {
            return price -> next.apply(apply(price));
        }

        static DiscountRule percentOff(double percent) {
            return price -> price - price * percent / 100;
        }
    }

    public static void main(String[] args) {
        DiscountRule festive = DiscountRule.percentOff(10);
        DiscountRule flatCoupon = price -> price - 50;

        double price = 1000;
        System.out.println("Festive only      : " + festive.apply(price));
        System.out.println("Coupon only       : " + flatCoupon.apply(price));
        System.out.println("Festive then coupon: " + festive.then(flatCoupon).apply(price));
    }
}
Output
Festive only      : 900.0
Coupon only       : 950.0
Festive then coupon: 850.0

5. How the Pieces Fit Together

A predicate and a function used in one flow An input string is tested by a Predicate, transformed by a Function, and the result is handed to a Consumer. Input " order shipped " Predicate test: keep it? Function apply: trim + upper Consumer accept: print
Figure 1: Small functional interfaces are building blocks. Streams connect them in exactly this way.

6. Important Points and Best Practices

  • Prefer the standard interfaces; create a custom one only when it adds meaning or needs checked exceptions.
  • Always add @FunctionalInterface to your own single-method interfaces.
  • Use primitive specialisations (IntPredicate, IntUnaryOperator) in performance-sensitive code.
  • Remember that Runnable, Callable and Comparator existed before Java 8 and are functional interfaces too.

7. Summary

  • A functional interface has exactly one abstract method.
  • Lambdas and method references get their type from a functional interface.
  • Predicate, Function, Consumer and Supplier cover most needs.
  • Default methods such as andThen and and let you compose behaviour.
  • @FunctionalInterface asks the compiler to enforce the single-method rule.

Related Tutorials

8. References