Functional Interfaces in 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
@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
defaultandstaticmethods. - Methods that match public methods of
Object, such asequals, do not count. That is whyComparatoris functional even though it declaresequals. @FunctionalInterfaceis optional, but it makes the compiler report an error if a second abstract method is added later.
3. The Core Built-in Interfaces
| Interface | Method | Shape | Typical use |
|---|---|---|---|
Predicate<T> | test(T) | T → boolean | filtering, validation |
Function<T,R> | apply(T) | T → R | converting values |
Consumer<T> | accept(T) | T → void | printing, saving |
Supplier<T> | get() | () → T | lazy defaults, factories |
UnaryOperator<T> | apply(T) | T → T | transforming in place |
BiFunction<T,U,R> | apply(T, U) | (T, U) → R | combining 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
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"));
}
}
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>.
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));
}
}
Festive only : 900.0 Coupon only : 950.0 Festive then coupon: 850.0
5. How the Pieces Fit Together
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
@FunctionalInterfaceto your own single-method interfaces. - Use primitive specialisations (
IntPredicate,IntUnaryOperator) in performance-sensitive code. - Remember that
Runnable,CallableandComparatorexisted 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,ConsumerandSuppliercover most needs.- Default methods such as
andThenandandlet you compose behaviour. @FunctionalInterfaceasks the compiler to enforce the single-method rule.
Related Tutorials
- Lambda Expressions
- Method References
- Default and Static Interface Methods
- Functional Interface in Java
8. References
Frequently Asked Questions (FAQ)
Q1. What is a functional interface?
An interface that has exactly one abstract method. It can also contain default and static methods. Lambdas and method references can be assigned to it.
Q2. Is @FunctionalInterface mandatory?
No. Any interface with a single abstract method is functional. The annotation only asks the compiler to check the rule and documents the intent.
Q3. Why is Comparator a functional interface when it declares two methods?
Its equals method has the same signature as a public method of Object, and such methods are not counted. Only compare is abstract.
Q4. What is the difference between Function and UnaryOperator?
UnaryOperator<T> extends Function<T,T>: the input and output types are the same. Use it when a value is transformed into another value of the same type.