Java Functional Interfaces

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 169 of 306

What Makes an Interface Functional

A functional interface is an interface with exactly one abstract method. That single method is what a lambda expression or method reference implements, which is why lambdas can only be used where a functional interface is expected.

The definition has a few details worth knowing:

  • Default and static methods don't count. A functional interface can have any number of them; only abstract methods count toward "exactly one".
  • Methods inherited from Object don't count. Redeclaring equals, hashCode or toString as abstract (as Comparator does with equals) doesn't stop an interface from being functional, because every implementation already has them.
  • Generic interfaces work — most functional interfaces are generic, like Function<T, R>.
public class Custom {
    @FunctionalInterface
    interface PriceRule {
        double apply(double price);

        default PriceRule then(PriceRule next) { return p -> next.apply(apply(p)); }
        static PriceRule percentOff(double pct) { return p -> p * (1 - pct / 100); }

        String toString();
        boolean equals(Object o);
    }

    public static void main(String[] args) {
        PriceRule festive = PriceRule.percentOff(10);
        PriceRule flat200 = p -> p - 200;
        System.out.println(festive.then(flat200).apply(4999));
    }
}

Output:

4299.1

PriceRule has one abstract method, apply; the default method then, the static factory percentOff and the redeclared Object methods don't affect its status. 10 % off 4999 is 4499.1, minus 200 is 4299.1.

The @FunctionalInterface Annotation

@FunctionalInterface is optional — any interface with one abstract method can be used with lambdas. The annotation documents the intent and makes the compiler verify it:

public class NotFunctional {
    @FunctionalInterface
    interface Shape {
        double area();
        double perimeter();
    }
}
NotFunctional.java:2: error: Unexpected @FunctionalInterface annotation
    @FunctionalInterface
    ^
  Shape is not a functional interface
    multiple non-overriding abstract methods found in interface Shape
1 error

Without the annotation, Shape would compile, and the problem would only appear where someone tried to use a lambda for it — or, worse, someone adding a second abstract method to an interface used with lambdas would break all those lambdas in other code. Annotate every interface you intend for lambdas.

The java.util.function Package

Before writing your own functional interface, check java.util.function. It contains 43 general-purpose interfaces, organised around four basic shapes:

InterfaceMethodTakesReturnsTypical use
Supplier<T>T get()nothinga TCreating values lazily, factories, defaults
Consumer<T>void accept(T t)a TnothingActions: print, save, send
Function<T, R>R apply(T t)a Tan RTransforming, mapping, extracting
Predicate<T>boolean test(T t)a TbooleanConditions, filters, validation

Variations on these shapes:

InterfaceMethodMeaning
BiFunction<T, U, R>R apply(T t, U u)Two inputs → result
BiConsumer<T, U>void accept(T t, U u)Action on two inputs (e.g. Map.forEach)
BiPredicate<T, U>boolean test(T t, U u)Condition on two inputs
UnaryOperator<T>T apply(T t)A Function<T, T>: same type in and out
BinaryOperator<T>T apply(T a, T b)A BiFunction<T, T, T>: combine two values of one type
import java.time.LocalDate;
import java.util.*;
import java.util.function.*;

public class Core {
    public static void main(String[] args) {
        Supplier<LocalDate> today = () -> LocalDate.of(2026, 11, 16);
        Consumer<String> shout = s -> System.out.println(s.toUpperCase());
        Function<String, Integer> wordCount = s -> s.split("\\s+").length;
        Predicate<String> isEmail = s -> s.contains("@");
        BiFunction<Double, Integer, Double> lineTotal = (price, qty) -> price * qty;
        BiConsumer<String, Integer> report = (k, v) -> System.out.println(k + "=" + v);
        BiPredicate<String, Integer> longerThan = (s, n) -> s.length() > n;
        UnaryOperator<String> trimLower = s -> s.strip().toLowerCase();
        BinaryOperator<Integer> larger = Math::max;

        System.out.println(today.get().getDayOfWeek());
        shout.accept("functional interfaces");
        System.out.println(wordCount.apply("lambdas make code shorter"));
        System.out.println(isEmail.test("asha@gocourse.in") + " " + isEmail.test("asha"));
        System.out.println(lineTotal.apply(12.5, 4));
        report.accept("stock", 40);
        System.out.println(longerThan.test("Coimbatore", 8));
        System.out.println("[" + trimLower.apply("  JAVA ") + "]");
        System.out.println(larger.apply(17, 42));
    }
}

Output:

MONDAY
FUNCTIONAL INTERFACES
4
true false
50.0
stock=40
true
[java]
42

Each variable is a different interface, and each is called through its own method name — get, accept, apply or test. The method names differ because they describe what the interface does; the lambdas themselves look alike.

Primitive specialisations

Generic interfaces work only with objects, so a Function<Integer, Integer> boxes every int into an Integer and unboxes it again. In tight loops or large data sets, that costs time and creates garbage. java.util.function therefore has primitive versions:

KindExamples
Primitive inputIntPredicate, IntConsumer, IntFunction<R>, LongPredicate, DoubleConsumer
Primitive outputToIntFunction<T>, ToLongFunction<T>, ToDoubleFunction<T>, IntSupplier, BooleanSupplier
Primitive in and outIntUnaryOperator, IntBinaryOperator, IntToDoubleFunction, DoubleUnaryOperator, ...
import java.util.function.*;

public class Prim {
    public static void main(String[] args) {
        IntPredicate even = n -> n % 2 == 0;
        IntUnaryOperator square = n -> n * n;
        IntBinaryOperator plus = Integer::sum;
        ToIntFunction<String> len = String::length;
        IntFunction<String> stars = n -> "*".repeat(n);
        DoubleSupplier pi = () -> Math.PI;
        IntToDoubleFunction half = n -> n / 2.0;

        System.out.println(even.test(10) + " " + square.applyAsInt(12) + " " + plus.applyAsInt(3, 4));
        System.out.println(len.applyAsInt("Chennai") + " " + stars.apply(5) + " " + half.applyAsDouble(7));
        System.out.printf("%.4f%n", pi.getAsDouble());
    }
}

Output:

true 144 7
7 ***** 3.5
3.1416

Primitive interfaces use method names that state the return type — applyAsInt, applyAsDouble, getAsDouble — so they can't be confused with the generic versions. The Stream API uses them for IntStream, LongStream and DoubleStream (mapToInt(ToIntFunction)).

Other functional interfaces in the JDK

Many older interfaces are also functional and work with lambdas: Runnable (void run()), Callable<V> (V call() throws Exception), Comparator<T> (int compare(T, T)), java.io.FileFilter, java.nio.file.PathMatcher, Thread.UncaughtExceptionHandler and others.

Composing Functional Interfaces

The standard interfaces have default and static methods that build new functions from existing ones. Composition lets you write small, named rules and combine them, instead of writing one large lambda.

import java.util.*;
import java.util.function.*;

public class Compose {
    record Student(String name, String city, int score, boolean feePaid) { }

    public static void main(String[] args) {
        Predicate<Student> passed = s -> s.score() >= 50;
        Predicate<Student> paid = Student::feePaid;
        Predicate<Student> fromChennai = s -> s.city().equals("Chennai");

        Predicate<Student> eligible = passed.and(paid);
        Predicate<Student> needsFollowUp = passed.negate().or(paid.negate());
        Predicate<String> notBlank = Predicate.not(String::isBlank);

        List<Student> all = List.of(
            new Student("Asha", "Chennai", 91, true), new Student("Ravi", "Madurai", 42, true),
            new Student("Meena", "Chennai", 77, false), new Student("Kumar", "Salem", 65, true));

        System.out.println("eligible:      " + names(all, eligible));
        System.out.println("follow up:     " + names(all, needsFollowUp));
        System.out.println("Chennai+elig.: " + names(all, fromChennai.and(eligible)));
        System.out.println("notBlank: " + notBlank.test("  ") + " " + notBlank.test("x"));

        Function<String, String> strip = String::strip;
        Function<String, String> upper = String::toUpperCase;
        Function<String, Integer> length = String::length;
        System.out.println(strip.andThen(upper).apply("  java "));
        System.out.println(upper.compose(strip).apply("  java "));
        System.out.println(strip.andThen(length).apply("  java "));
        System.out.println(Function.<String>identity().apply("same"));

        List<String> audit = new ArrayList<>();
        Consumer<Student> logIt = s -> audit.add("log " + s.name());
        Consumer<Student> mailIt = s -> audit.add("mail " + s.name());
        all.stream().filter(eligible).forEach(logIt.andThen(mailIt));
        System.out.println(audit);

        BinaryOperator<Student> topScorer = BinaryOperator.maxBy(Comparator.comparingInt(Student::score));
        System.out.println("top: " + all.stream().reduce(topScorer).map(Student::name).orElse("-"));
    }

    static List<String> names(List<Student> list, Predicate<Student> p) {
        return list.stream().filter(p).map(Student::name).toList();
    }
}

Output:

eligible:      [Asha, Kumar]
follow up:     [Ravi, Meena]
Chennai+elig.: [Asha]
notBlank: false true
JAVA
JAVA
4
same
[log Asha, mail Asha, log Kumar, mail Kumar]
top: Asha
MethodResult
p1.and(p2), p1.or(p2), p.negate()Logical AND, OR, NOT of predicates (with short-circuiting)
Predicate.not(p) (Java 11+)Negation, convenient with method references: Predicate.not(String::isBlank)
f.andThen(g)First f, then g on the result
f.compose(g)First g, then f — the reverse order of andThen
Function.identity()A function that returns its input unchanged
c1.andThen(c2) (Consumer)Run c1, then c2, on the same value
BinaryOperator.minBy(cmp) / maxBy(cmp)Keep the smaller/larger of two values
  • eligible combines two rules; needsFollowUp expresses "failed or not paid" without writing any new logic.
  • strip.andThen(upper) and upper.compose(strip) produce the same result here because both strip first and uppercase second; compose is just written in the other direction.
  • logIt.andThen(mailIt) runs both actions for each eligible student.
  • BinaryOperator.maxBy builds a "keep the higher scorer" operator that reduce applies across the list.

Comparator has the richest set of composition methods (comparing, thenComparing, reversed, nullsFirst), covered in the Stream Sort lesson.

Writing Your Own Functional Interface

Create a custom functional interface when:

  • a name from your domain makes code clearer (PriceRule, Validator<T>, RetryPolicy) than a generic Function<Double, Double>;
  • you need more parameters than the standard interfaces provide (there's no TriFunction);
  • the method must declare a checked exception — none of the java.util.function interfaces do.

The last case is the most common reason in practice, and the subject of the practical example.

Practical Example: Functional Interfaces That Allow Checked Exceptions

Function.apply can't throw checked exceptions, so methods like Files.readString, which throws IOException, can't be used directly in a map or any other place that expects a Function. A small custom functional interface that does declare throws Exception, plus static adapter methods that turn it into a standard Function, solves this once for the whole code base.

import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.function.*;

public class Throwing {
    @FunctionalInterface
    interface ThrowingFunction<T, R> {
        R apply(T t) throws Exception;

        static <T, R> Function<T, R> unchecked(ThrowingFunction<T, R> f) {
            return t -> {
                try {
                    return f.apply(t);
                } catch (RuntimeException e) {
                    throw e;
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            };
        }

        static <T, R> Function<T, Optional<R>> lenient(ThrowingFunction<T, R> f, BiConsumer<T, Exception> onError) {
            return t -> {
                try {
                    return Optional.ofNullable(f.apply(t));
                } catch (Exception e) {
                    onError.accept(t, e);
                    return Optional.empty();
                }
            };
        }
    }

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("imports");
        Files.writeString(dir.resolve("jan.csv"), "a\nb\nc\n");
        Files.writeString(dir.resolve("feb.csv"), "d\ne\n");
        List<Path> files = List.of(dir.resolve("jan.csv"), dir.resolve("missing.csv"), dir.resolve("feb.csv"));

        Function<Path, Optional<Long>> countLines = ThrowingFunction.lenient(
            p -> {
                try (var lines = Files.lines(p)) {
                    return lines.count();
                }
            },
            (p, e) -> System.out.println("  skipped " + p.getFileName() + ": " + e.getClass().getSimpleName()));

        long total = files.stream().map(countLines).flatMap(Optional::stream).mapToLong(Long::longValue).sum();
        System.out.println("total lines: " + total);

        try {
            files.stream().map(ThrowingFunction.unchecked(Files::readString)).forEach(s -> { });
        } catch (UncheckedIOException e) {
            System.out.println("strict mode failed: " + e.getCause().getClass().getSimpleName());
        }
    }
}

Output:

  skipped missing.csv: NoSuchFileException
total lines: 5
strict mode failed: NoSuchFileException

How it works:

  1. ThrowingFunction<T, R> is a functional interface like Function, except its method declares throws Exception. Lambdas and method references that throw checked exceptions — Files::readString, a block that calls Files.lines — are valid implementations.
  2. unchecked adapts it into a standard Function: checked exceptions are wrapped (IOException in UncheckedIOException, everything else in RuntimeException), with the original kept as the cause. Unchecked exceptions are rethrown unchanged. This is the "strict" mode: the first failure stops the stream.
  3. lenient adapts it differently: a failure is reported to an error handler (a BiConsumer receiving the input and the exception) and turned into an empty Optional, so processing continues with the next file. flatMap(Optional::stream) then keeps only the successful results.
  4. Resource safety inside the lambda: Files.lines returns a stream holding an open file, so the lambda closes it with try-with-resources. Because the interface allows checked exceptions, the block can use Files.lines directly.
  5. The results: the two existing files have 3 and 2 lines; the missing file is reported and skipped in lenient mode, and causes a clear failure in strict mode.

Libraries such as Vavr and Apache Commons Lang (FailableFunction) ship ready-made versions of these interfaces; many projects define their own small set exactly like this one.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Functional Interfaces and get answers drawn from it.

Signed-in readers only.