Functional interfaces
What you will learn
A functional interface describes a single operation, such as deciding whether an item is in stock or converting a price into a label. A lambda supplies an implementation of that operation without writing a separate named class. Java still checks the parameter and result types at compile time.
- Identify the functional method and target type of a lambda.
- Select Predicate, Function, Consumer, Supplier or an operator interface for a task.
- Distinguish primitive specializations from boxed generic values.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed.
Give a decision a name
import java.util.*;import java.util.function.*;public class Main {
public static void main(String[] args) { Predicate<Integer> available = units -> units > 0; System.out.println(available.test(3)); System.out.println(available.test(0)); }}Expected output:
truefalseThe variable type establishes a one-argument boolean operation. Calling test evaluates the body with the supplied number.
Rules and mental model
A functional interface has one abstract operation after the language rules for inherited methods and public Object methods are applied. Default and static methods do not add abstract operations. @FunctionalInterface is optional, but asks the compiler to check the contract. A sealed interface is not a functional interface. A lambda needs a target functional interface, obtained from an assignment, argument or cast; var f = x -> x + 1; alone has no target type. In (int x) -> x + 1, the parameter is explicit; in x -> x + 1, the compiler infers it. Zero parameters use (), multiple parameters use parentheses, and a block body returning a value uses return. A lambda expression creates or obtains an implementation; its body executes when the functional method is invoked, not merely when the expression is evaluated.
Use Predicate<T> for a boolean decision (test), Function<T,R> for a transformation (apply), Consumer<T> for an action with no result (accept), and Supplier<T> for obtaining a value without an argument (get). UnaryOperator<T> extends Function for a same-type input/result, and BinaryOperator<T> extends BiFunction for two inputs of the same type and a same-type result. Primitive specializations such as IntPredicate, IntUnaryOperator, IntSupplier and ToIntFunction avoid the corresponding boxing at the interface boundary; generic type arguments cannot be primitive. Use a named domain interface when its meaning or exception contract matters more than a generic shape. Checked exceptions escaping a lambda must be allowed by the target method. A lambda is not inherently pure: it can mutate state or throw exceptions.
Transform inventory labels and perform an action
import java.util.*;import java.util.function.*;public class Main {
public static void main(String[] args) { Function<String, String> label = name -> "Item: " + name.trim(); Consumer<String> print = text -> System.out.println(text); Supplier<String> defaultName = () -> "unknown"; print.accept(label.apply(" pencil ")); print.accept(label.apply(defaultName.get())); }}Expected output:
Item: pencilItem: unknownEach interface expresses a different data flow: get produces, apply transforms, and accept consumes.
Use primitive and same-type operators
import java.util.*;import java.util.function.*;public class Main {
public static void main(String[] args) { IntUnaryOperator addFee = cents -> cents + 25; UnaryOperator<String> prefix = s -> "#" + s; BinaryOperator<Integer> chooseLarger = (a, b) -> Math.max(a, b); System.out.println(addFee.applyAsInt(100)); System.out.println(prefix.apply("A7")); System.out.println(chooseLarger.apply(3, 8)); }}Expected output:
125#A78The primitive operator takes and returns int. The generic operators preserve the declared value type.
Define a domain-specific functional interface
import java.util.*;import java.util.function.*;public class Main { @FunctionalInterface interface Charge { int cents(int distance); default String description() { return "Delivery charge"; } } public static void main(String[] args) { Charge delivery = distance -> distance * 2; System.out.println(delivery.cents(6)); System.out.println(delivery.description()); }}Expected output:
12Delivery chargeThe default method does not interfere with the one abstract operation. A caller uses the domain-specific method name.
Common mistakes
Do not call every one-method interface functional without checking its inherited abstract contracts. Do not expect lambda creation to run the body or infer a target from var alone.
Practice
Create an IntPredicate that accepts even quantities, an IntUnaryOperator that doubles them, and a Consumer<String> that prints a label. For the input quantities 3, 4 and 0, print only accepted values as Packed: N after doubling. The output must be two lines.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functional interfaces — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
Which interface models a boolean decision about an item?
When does `Supplier<Integer> s = () -> 7;` execute its body?
Why is `var f = x -> x + 1;` rejected?
Which method invokes IntUnaryOperator?
Does adding a default method prevent an otherwise functional interface from being functional?