Java Functional Interfaces
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
Objectdon't count. Redeclaringequals,hashCodeortoStringas abstract (asComparatordoes withequals) 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:
| Interface | Method | Takes | Returns | Typical use |
|---|---|---|---|---|
Supplier<T> | T get() | nothing | a T | Creating values lazily, factories, defaults |
Consumer<T> | void accept(T t) | a T | nothing | Actions: print, save, send |
Function<T, R> | R apply(T t) | a T | an R | Transforming, mapping, extracting |
Predicate<T> | boolean test(T t) | a T | boolean | Conditions, filters, validation |
Variations on these shapes:
| Interface | Method | Meaning |
|---|---|---|
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:
| Kind | Examples |
|---|---|
| Primitive input | IntPredicate, IntConsumer, IntFunction<R>, LongPredicate, DoubleConsumer |
| Primitive output | ToIntFunction<T>, ToLongFunction<T>, ToDoubleFunction<T>, IntSupplier, BooleanSupplier |
| Primitive in and out | IntUnaryOperator, 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
| Method | Result |
|---|---|
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 |
eligiblecombines two rules;needsFollowUpexpresses "failed or not paid" without writing any new logic.strip.andThen(upper)andupper.compose(strip)produce the same result here because both strip first and uppercase second;composeis just written in the other direction.logIt.andThen(mailIt)runs both actions for each eligible student.BinaryOperator.maxBybuilds a "keep the higher scorer" operator thatreduceapplies 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 genericFunction<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.functioninterfaces 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:
ThrowingFunction<T, R>is a functional interface likeFunction, except its method declaresthrows Exception. Lambdas and method references that throw checked exceptions —Files::readString, a block that callsFiles.lines— are valid implementations.uncheckedadapts it into a standardFunction: checked exceptions are wrapped (IOExceptioninUncheckedIOException, everything else inRuntimeException), with the original kept as the cause. Unchecked exceptions are rethrown unchanged. This is the "strict" mode: the first failure stops the stream.lenientadapts it differently: a failure is reported to an error handler (aBiConsumerreceiving the input and the exception) and turned into an emptyOptional, so processing continues with the next file.flatMap(Optional::stream)then keeps only the successful results.- Resource safety inside the lambda:
Files.linesreturns a stream holding an open file, so the lambda closes it with try-with-resources. Because the interface allows checked exceptions, the block can useFiles.linesdirectly. - 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.