Functional Interfaces in Java: SAM Rules, Lambdas and Runnable Examples

Build functional interfaces from zero, replace an anonymous class with a lambda, select standard interfaces by shape, and avoid common compiler traps.

KnowledgeGate Team

Exam prep & CS education

Updated 10 Nov 20265 min read
Functional Interfaces in Java: SAM Rules, Lambdas and Runnable Examples

A functional interface has one logical abstract method, even when it also declares default or static methods. The @FunctionalInterface annotation asks the compiler to enforce that rule; it does not create lambda support. Lambdas gain their parameter and return contracts from a target functional-interface type, and composition order determines which function runs first.

What makes an interface functional?

Under section 9.8 of Oracle's Java Language Specification, a functional interface has one logical abstract instance method, called its single abstract method or SAM. @FunctionalInterface is an optional compiler check. An unannotated interface that satisfies the rule still works with lambdas.

java
@FunctionalInterface
interface PriceRule {
    int finalPrice(int markedPrice);

    default String label() { return "offer"; }
    static boolean valid(int price) { return price >= 0; }
}

Only finalPrice(int) is abstract. The default method has an implementation, while the static method belongs to the interface itself.

This version fails at compile time because the annotation exposes two unrelated abstract methods:

java
@FunctionalInterface
interface BrokenRule {
    int apply(int x);
    boolean test(int x);
}

Two specification details prevent bad counting. An abstract declaration matching a public method of Object, such as boolean equals(Object other), does not count towards the SAM. Also, identical inherited declarations such as int map(int x) from two parent interfaces can describe one logical function method. These are JLS rules, not a shortcut that makes any repeated methods acceptable.

Replace an anonymous class with a lambda

Here is a 10 percent discount in anonymous-class form:

java
PriceRule oldStyle = new PriceRule() {
    @Override
    public int finalPrice(int price) {
        return price - price / 10;
    }
};

The equivalent lambda is PriceRule tenPercentOff = price -> price - price / 10;. price is the parameter, -> connects input to behaviour, and the expression is the returned result.

java
@FunctionalInterface
interface PriceRule {
    int finalPrice(int markedPrice);
}

public class FunctionalInterfaceDemo {
    public static void main(String[] args) {
        PriceRule tenPercentOff = price -> price - price / 10;
        System.out.println(tenPercentOff.finalPrice(1250));
    }
}

The output is exactly 1125. With deliberate integer arithmetic, 1250 / 10 = 125, then 1250 - 125 = 1125. The lambda removes anonymous-class boilerplate, but evaluating it still produces an instance whose target type is PriceRule, and the call still follows the finalPrice(int) contract.

Side-by-side code-to-execution flow diagram showing PriceRule, markedPrice 1250, discount 125, finalPrice 1125, with console output 1125.

Choose the right built-in functional interface

The java.util.function package covers common shapes:

Type

Shape and concrete call

Predicate<Integer>

score -> score >= 40: test(39) is false, test(40) is true

Function<String, Integer>

String::length: apply("KnowledgeGate") is 13

Consumer<String>

System.out::println: accept("Ready") prints Ready

Supplier<List<String>>

ArrayList::new: get() supplies a list of size 0

UnaryOperator<Integer>

x -> x * x: apply(7) is 49

Choose by shape: T -> boolean suggests Predicate<T>, T -> R a Function<T,R>, T -> void a Consumer<T>, no input to T a Supplier<T>, and T -> T a UnaryOperator<T>.

Primitive specialisations can avoid boxing. In an integer-heavy loop, IntPredicate positive = n -> n > 0 avoids repeatedly converting between int and Integer. Treat that as a useful option, not a claim of better speed without measurement.

Target typing, method references and composition order

Context supplies a lambda's target type:

java
PriceRule a = p -> p - 100;
IntUnaryOperator b = p -> p - 100;

The lambda alone has no useful standalone type. Assignment or a method parameter supplies its contract, so overloaded methods can be ambiguous when two target types fit.

Method references shorten lambdas when the referenced name is clearer:

java
Function<String, Integer> parse = Integer::parseInt;       // s -> Integer.parseInt(s)
Predicate<String> prefix = "KnowledgeGate"::startsWith;   // s -> "KnowledgeGate".startsWith(s)
ToIntFunction<String> length = String::length;             // s -> s.length()
Supplier<List<String>> lists = ArrayList::new;              // () -> new ArrayList<>()

These are static, bound-instance, unbound-instance, and constructor references respectively.

Order matters in composition:

java
Function<Integer, Integer> addFee = x -> x + 50;
Function<Integer, Integer> discount10 = x -> x - x / 10;

From 1000, addFee.andThen(discount10) first reaches 1050, then subtracts 1050 / 10 = 105, producing 945. Reversing the chain with discount10.andThen(addFee) first gives 1000 - 100 = 900, then 900 + 50 = 950. For f.andThen(g), f runs first. For f.compose(g), g runs first.

Two horizontal pipelines compare addFee and discount10 in different orders: 1000 becomes 945 in Pipeline A and 950 in Pipeline B, a 5-point difference.

Compiler errors and semantic traps

Recognise these three broken and fixed patterns:

  • Too many abstract methods: annotated BrokenRule fails; keep one logical SAM or remove lambda use.

  • Captured local mutation: int bonus = 50; Function<Integer,Integer> f = x -> x + bonus; bonus++; fails because bonus is not effectively final. Leave it unchanged, or declare final int bonus = 50.

  • Checked exception: Function<Path,String> read = p -> Files.readString(p); fails because Function.apply does not declare IOException. Catch and wrap it inside the lambda, or define a custom functional interface whose SAM declares throws IOException.

Two other traps compile. Inside a lambda, this is the enclosing instance, unlike this inside an anonymous class, which refers to that anonymous object. Also, Predicate<Integer> positive = n -> n > 0 compiles, but positive.test(null) throws NullPointerException when Java tries to unbox that particular null value. This does not make every lambda null-unsafe.

Effectively final locals concern whether a captured variable is reassigned. That is separate from object immutability, explained further in Java string handling, the string pool and immutability.

How exams and interviews test functional interfaces

Use a four-step checklist:

  1. Count logical abstract methods using the JLS rule.

  2. Ignore default and static methods.

  3. Match input and output to Predicate, Function, Consumer, or Supplier.

  4. Trace compose and andThen from the function that actually runs first.

For Predicate<String> longName = s -> s.length() >= 5, longName.test("Java") is false because the length is 4; longName.test("Lambda") is true because the length is 6. Identification check: is an interface with one abstract method and two default methods valid? Yes, it is functional.

For interview depth, be ready to explain why the annotation is a useful compiler check, how lambda and anonymous-class this bindings differ, and when a method reference reads more clearly than a lambda.

Practice task, the short version and next step

Define interface Transformer { int apply(int x); }, then create Transformer doubleIt = x -> x * 2 and Transformer addThree = x -> x + 3. The nested call addThree.apply(doubleIt.apply(8)) produces 19 because 8 * 2 = 16 and 16 + 3 = 19. Now declare the same operations as Function<Integer,Integer> doubleFunction = x -> x * 2 and Function<Integer,Integer> addFunction = x -> x + 3. Then doubleFunction.andThen(addFunction).apply(8) also gives 19, while addFunction.andThen(doubleFunction).apply(8) gives 22.

If basic runnable loops and methods need more work first, use classic programs in C, Java and Python, then return to this exercise.

The short version:

  • A functional interface has one logical abstract method.

  • @FunctionalInterface is optional but protective.

  • A lambda needs a target type.

  • Built-in interfaces cover the common shapes.

  • Composition order can change the result.

For a broader route from Java basics, continue with Complete Java. For structured Java practice, use Java: Concepts, MCQs and Coding Questions. The Coding & DSA category lets you compare the available coding paths.