Skip to lesson

Write your own functional interface

When no interface in java.util.function has the shape you need, you write your own: an interface with exactly one abstract method, marked @FunctionalInterface. Lambdas work with it exactly as with the built-in ones.

When the built-in interfaces do not fit

Start with the built-in interfaces: every Java developer knows them and every library accepts them. Write your own interface only when none of them fits.

Example 1 · Three inputs: a TriFunction or a record

TriFunctionDemo.javaJava
import java.util.function.Function;
@FunctionalInterfaceinterface TriFunction<A, B, C, R> {    R apply(A a, B b, C c);}
record FeeInput(int tuition, int hostel, int scholarshipPercent) {}
public class TriFunctionDemo {    public static void main(String[] args) {        TriFunction<Integer, Integer, Integer, Integer> payable =                (tuition, hostel, percent) -> tuition - tuition * percent / 100 + hostel;        System.out.println("TriFunction: Rs. " + payable.apply(120000, 45000, 25));
        Function<FeeInput, Integer> payable2 =                f -> f.tuition() - f.tuition() * f.scholarshipPercent() / 100 + f.hostel();        System.out.println("Record + Function: Rs. " + payable2.apply(new FeeInput(120000, 45000, 25)));    }}
Output
TriFunction: Rs. 135000
Record + Function: Rs. 135000

What this code does

  • TriFunction is a normal generic interface with one abstract method, so a three-parameter lambda fits it. The scholarship applies only to tuition: 120000 - 30000 + 45000.
  • The record version needs no new interface and gives the three values names. Prefer it when the inputs belong together; use a TriFunction when they do not.

There are three reasons to write your own:

  • Three or more inputs. Java stops at two: there is BiFunction but no TriFunction.
  • A checked exception. Function.apply declares no exceptions, so a lambda that calls a method throwing IOException cannot be a Function. Your own interface can declare throws.
  • A domain name that explains itself. DiscountRule with int apply(int amount) says more in a shop app than IntUnaryOperator, and it can carry its own helper methods.

For three inputs, first ask whether the values belong together. A fee from tuition, hostel fee and scholarship percent can be one record, and then a plain one-input Function is enough. When the inputs really are separate, a small TriFunction<A, B, C, R> interface is fine. Use the domain-name reason sparingly: a custom type does not plug into library methods that expect a built-in one, so you may need to adapt it.

The @FunctionalInterface annotation

@FunctionalInterface is an annotation that makes the Java compiler check that an interface has exactly one abstract method. If a second one is added, the compiler reports an error at once, instead of lambdas breaking elsewhere.

Any interface with one abstract method already works with lambdas. @FunctionalInterface adds a compiler check: if the interface does not have exactly one abstract method, compilation fails with "Unexpected @FunctionalInterface annotation".

Example 2 · Error: @FunctionalInterface with two abstract methods

AnnotationErrorDemo.javaJava
@FunctionalInterfaceinterface FeeRule {    int apply(int amount);    String describe();}
public class AnnotationErrorDemo {    public static void main(String[] args) {        FeeRule lateFee = amount -> amount + 500;        System.out.println(lateFee.apply(10000));    }}
Sample compiler output
AnnotationErrorDemo.java:1: error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
  FeeRule is not a functional interface
    multiple non-overriding abstract methods found in interface FeeRule
AnnotationErrorDemo.java:9: error: incompatible types: FeeRule is not a functional interface
        FeeRule lateFee = amount -> amount + 500;
                          ^
    multiple non-overriding abstract methods found in interface FeeRule
2 errors

What this code does

  • The annotation makes the compiler count the abstract methods. There are two, apply and describe, so the first error points at the interface itself, the place you must fix. The lambda line fails too, because FeeRule is no longer a functional interface.
  • Fix: make describe a default method with a body, such as default String describe() { return "fee rule"; }. Then apply is the only abstract method and the lambda compiles.

That protects every lambda that uses the interface. Without the annotation, a teammate could add a second abstract method, and every lambda in the project would break at once, far from the real cause. With it, the error appears right on the interface. What does not count as an abstract method: default methods, static methods, and abstract methods that match a public method of Object, such as boolean equals(Object o). Every object already has those, so a lambda never needs to supply them.

Default methods for chaining

The built-in interfaces chain because of default methods such as Predicate.and and Function.andThen. Your own interface can do the same: add a default method that returns a new instance of the interface, written as a lambda that calls this and the other one.

Example 3 · Default and static methods for chaining

DiscountRuleDemo.javaJava
@FunctionalInterfaceinterface DiscountRule {    int apply(int amount);
    default DiscountRule then(DiscountRule next) {        return amount -> next.apply(this.apply(amount));    }
    static DiscountRule flat(int off) {        return amount -> Math.max(0, amount - off);    }
    static DiscountRule percent(int p) {        return amount -> amount - amount * p / 100;    }}
public class DiscountRuleDemo {    public static void main(String[] args) {        DiscountRule festive = DiscountRule.flat(100).then(DiscountRule.percent(10));        DiscountRule student = DiscountRule.percent(10).then(DiscountRule.flat(100));        DiscountRule firstOrder = amount -> amount >= 500 ? amount - 150 : amount;
        System.out.println("Festive on 1000: " + festive.apply(1000));        System.out.println("Student on 1000: " + student.apply(1000));        System.out.println("First order on 1000: " + firstOrder.apply(1000));        System.out.println("Flat 100 on 60: " + DiscountRule.flat(100).apply(60));    }}
Output
Festive on 1000: 810
Student on 1000: 800
First order on 1000: 850
Flat 100 on 60: 0

What this code does

  • then is a default method that returns a new DiscountRule as a lambda. Inside it, this is the rule it was called on, so flat(100).then(percent(10)) takes 100 off first: 900, then 810.
  • flat and percent are static factories. Math.max(0, ...) handles the edge case of a discount bigger than the bill, so 60 becomes 0, not -40.
  • A lambda written at the call site, like firstOrder, works too, because the interface has exactly one abstract method.

For example, default DiscountRule then(DiscountRule next) { return amount -> next.apply(this.apply(amount)); }. Inside a default method, this is the rule object the method was called on, so flat50.then(tenPercent) first applies flat50. static methods in the interface make good factories, methods that build ready-made instances: DiscountRule.percent(10) returns a lambda for 10% off. Callers then read like plain English: DiscountRule.flat(50).then(DiscountRule.percent(10)).

Checked exceptions inside lambdas

A checked exception, such as IOException, must be caught or declared with throws. Function.apply declares none, so a lambda that calls a method throwing IOException does not compile.

Example 4 · Error: a Function lambda cannot throw IOException

CheckedErrorDemo.javaJava
import java.io.IOException;import java.util.function.Function;
public class CheckedErrorDemo {    static String loadMarksSheet(String roll) throws IOException {        if (roll.startsWith("X")) {            throw new IOException("no marks sheet for " + roll);        }        return roll + ": 78, 84, 91";    }
    public static void main(String[] args) {        Function<String, String> loader = roll -> loadMarksSheet(roll);        System.out.println(loader.apply("CS101"));    }}
Sample compiler output
CheckedErrorDemo.java:13: error: unreported exception IOException; must be caught or declared to be thrown
        Function<String, String> loader = roll -> loadMarksSheet(roll);
                                                                ^
1 error

What this code does

  • loadMarksSheet declares throws IOException, a checked exception. The lambda implements Function.apply, which declares no exceptions, so the exception has nowhere to go.
  • Adding throws IOException to main does not help: the call happens inside the lambda, and the lambda body is checked against apply.

Example 5 · Three fixes: handle, wrap, or a throwing interface

CheckedFixDemo.javaJava
import java.io.IOException;import java.io.UncheckedIOException;import java.util.function.Function;
@FunctionalInterfaceinterface 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 (Exception e) {                throw new RuntimeException(e.getMessage(), e);            }        };    }}
public class CheckedFixDemo {    static String loadMarksSheet(String roll) throws IOException {        if (roll.startsWith("X")) {            throw new IOException("no marks sheet for " + roll);        }        return roll + ": 78, 84, 91";    }
    public static void main(String[] args) {        // fix 1: handle it inside the lambda        Function<String, String> withDefault = roll -> {            try {                return loadMarksSheet(roll);            } catch (IOException e) {                return roll + ": not uploaded yet";            }        };        System.out.println(withDefault.apply("CS101"));        System.out.println(withDefault.apply("X999"));
        // fix 2: wrap it in an unchecked exception        Function<String, String> strict = roll -> {            try {                return loadMarksSheet(roll);            } catch (IOException e) {                throw new UncheckedIOException(e);            }        };        try {            strict.apply("X999");        } catch (UncheckedIOException e) {            System.out.println("Stopped: " + e.getCause().getMessage());        }
        // fix 3: your own interface that may throw, adapted to Function        Function<String, String> adapted = ThrowingFunction.unchecked(roll -> loadMarksSheet(roll));        System.out.println(adapted.apply("CS102"));    }}
Output
CS101: 78, 84, 91
X999: not uploaded yet
Stopped: no marks sheet for X999
CS102: 78, 84, 91

What this code does

  • Fix 1 suits a missing value you can live with. Fix 2 keeps the failure loud but lets the lambda fit Function; the caller still sees the original message through getCause().
  • Fix 3: ThrowingFunction.apply declares throws Exception, so roll -> loadMarksSheet(roll) compiles as one. The static unchecked adapter wraps it in a normal Function that rethrows any failure as a RuntimeException.

The Java compiler reports unreported exception IOException; must be caught or declared to be thrown, because a lambda body follows the rules of the interface method it implements. There are three honest fixes. First, handle it inside the lambda with try/catch, when you know what to do, such as using a default value. Second, wrap it in an unchecked exception: catch (IOException e) { throw new UncheckedIOException(e); }, so it still stops the program but fits Function. Third, write your own interface whose method declares the exception, such as ThrowingFunction<T, R> with R apply(T t) throws Exception, plus a static adapter that turns it into a normal Function.

Never catch the exception and ignore it. An empty catch hides a missing file or a bad record, and the program carries on with wrong data.

Fix the error

Fix the checked exception

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

load can throw IOException. The reader must still be a Function.

import java.io.IOException;
import java.util.function.Function;
public class ReadFix {
static String load(String file) throws IOException { return "data from " + file; }
public static void main(String[] args) {
Function<String, String> reader = f -> load(f);
System.out.println(reader.apply("marks.txt"));
}
}

Error

ReadFix.java:8: error: unreported exception IOException; must be caught or declared to be thrown
        Function<String, String> reader = f -> load(f);
UncheckedIOException in java.io is a ready-made runtime wrapper for IOException. For other checked exceptions, wrap in RuntimeException or your own unchecked exception.

Interview point: Comparator has many methods

Comparator<T> has reversed, thenComparing, comparing, naturalOrder and more, yet it is marked @FunctionalInterface and a lambda can be a comparator. The reason is the counting rule.

Example 6 · Comparator is functional despite its many methods

ComparatorFunctionalDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
@FunctionalInterfaceinterface MarksCheck {    boolean check(int marks);
    boolean equals(Object other);   // matches Object's method, so it does not count
    default MarksCheck strict() {        return m -> check(m) && m >= 50;    }}
public class ComparatorFunctionalDemo {    public static void main(String[] args) {        Comparator<String> byLength = (a, b) -> Integer.compare(a.length(), b.length());        List<String> cities = new ArrayList<>(List.of("Chennai", "Goa", "Pune"));        cities.sort(byLength.reversed().thenComparing(Comparator.naturalOrder()));        System.out.println(cities);
        MarksCheck pass = m -> m >= 35;        System.out.println("42 pass? " + pass.check(42) + ", strict? " + pass.strict().check(42));    }}
Output
[Chennai, Pune, Goa]
42 pass? true, strict? false

What this code does

  • The lambda supplies only compare. reversed and thenComparing are default methods and naturalOrder is static, so they come free with the interface.
  • MarksCheck copies the same pattern: it declares equals(Object), which every object already has, plus a default method, and still compiles with @FunctionalInterface.

reversed and thenComparing are default methods, and comparing, naturalOrder and reverseOrder are static, so none of them count. Comparator also declares boolean equals(Object obj), which is abstract but matches a public method of Object, so it does not count either. That leaves exactly one abstract method: int compare(T o1, T o2). So the honest answer is: a functional interface is about the number of abstract methods that a lambda must supply, not about the total number of methods.

Next step

Check your understanding

12 quick questions