Chapter 70 of 77

Functional Interfaces in Java

Sometimes we want to pass behaviour to a method, not just data. For example, "sort these students, and here is how to compare them", or "filter these marks, and here is the rule for which ones to keep". You have already done this once: in the Comparable and Comparator chapter, we passed a Comparator object to sort(), and that object carried the comparison logic.

Comparator is an example of a special kind of interface called a functional interface. Functional interfaces are the foundation of modern Java features such as lambda expressions and the Stream API, so it is worth understanding them well.

A functional interface is an interface that has exactly one abstract method. It represents a single piece of behaviour, like "compare two things" or "check a condition".

Examples You Already Know

Java has had functional interfaces for a long time, even before the term existed:

Interface

Single abstract method

Behaviour it represents

Comparator<T>

int compare(T a, T b)

Compare two objects

Comparable<T>

int compareTo(T other)

Compare this object with another

Runnable

void run()

A task to run

Iterable<T>

Iterator<T> iterator()

Provide an iterator

Each has exactly one method that must be implemented, so each is a functional interface. (Not every functional interface is meant to be used as a function, though. Comparable and Iterable are normally implemented by classes, while Comparator and Runnable are the classic "behaviour" interfaces.)

Creating Your Own Functional Interface

Let's create a functional interface for greeting someone, and a method that accepts any greeting behaviour:

@FunctionalInterface
interface Greeter {
    void greet(String name);
}

class PoliteGreeter implements Greeter {
    @Override
    public void greet(String name) {
        System.out.println("Good morning, " + name + "!");
    }
}

class Main {

    static void welcome(Greeter greeter) {
        greeter.greet("John");
        greeter.greet("Priya");
    }

    public static void main(String[] args) {

        // 1. A normal class
        welcome(new PoliteGreeter());

        // 2. An anonymous class
        welcome(new Greeter() {
            @Override
            public void greet(String name) {
                System.out.println("Hey " + name + "!");
            }
        });
    }
}

Output:

Good morning, John!
Good morning, Priya!
Hey John!
Hey Priya!

The welcome() method does not know or care how the greeting is done. It just calls greet(). We decide the behaviour when we call the method. This is the main idea behind functional interfaces: behaviour becomes something we can pass around like a value.

The @FunctionalInterface Annotation

The @FunctionalInterface annotation is optional, but it is good practice. It tells the compiler: "this interface must have exactly one abstract method". If someone later adds a second abstract method, compilation fails:

@FunctionalInterface
interface Greeter {
    void greet(String name);
    void wave();               // second abstract method
}
error: Unexpected @FunctionalInterface annotation
  Greeter is not a functional interface
    multiple non-overriding abstract methods found in interface Greeter

An interface with one abstract method is a functional interface even without the annotation. The annotation simply protects it from accidental changes.

What Is Allowed in a Functional Interface?

"Exactly one abstract method" does not mean "exactly one method". A functional interface can also have:

  • Any number of default methods

  • Any number of static methods

  • Abstract methods that match public methods of Object, such as toString() or equals(). These don't count, because every class already gets them from Object.

@FunctionalInterface
interface Shape {
    double area();                       // the single abstract method

    default void describe() {            // default method: allowed
        System.out.println("Area = " + area());
    }

    static Shape square(double side) {   // static method: allowed
        return new Shape() {
            @Override
            public double area() {
                return side * side;
            }
        };
    }

    String toString();                   // from Object: does not count
}

class Main {
    public static void main(String[] args) {
        Shape s = Shape.square(4);
        s.describe();
    }
}

Output:

Area = 16.0

This is exactly how Comparator works: it has one abstract method, compare(), plus helpful default methods like reversed() and thenComparing().

A Shorter Way: A Quick Look at Lambdas

Writing an anonymous class every time is a lot of code for one small method. Because a functional interface has only one method to implement, Java can figure out which method we mean. So instead of this:

welcome(new Greeter() {
    @Override
    public void greet(String name) {
        System.out.println("Hey " + name + "!");
    }
});

we can write just the parameter and the body:

welcome(name -> System.out.println("Hey " + name + "!"));

This shorthand is called a lambda expression. Read name -> ... as "given name, do this". Lambdas only work where a functional interface is expected. The next chapter covers lambda syntax in detail. For the rest of this chapter, you only need to recognise the basic shape:

x -> expression           one parameter
(a, b) -> expression      two parameters
() -> expression          no parameters

Built-in Functional Interfaces: java.util.function

Instead of creating our own interface for every situation, Java 8 added the java.util.function package with ready-made functional interfaces. Four of them are the most important:

Interface

Method

Takes

Returns

Use it to

Predicate<T>

test(T t)

T

boolean

Check a condition

Function<T, R>

apply(T t)

T

R

Convert one value into another

Consumer<T>

accept(T t)

T

nothing

Do something with a value

Supplier<T>

get()

nothing

T

Produce a value

And a few useful variations:

Interface

Method

Meaning

BiFunction<T, U, R>

apply(T t, U u)

Two inputs, one result

BiPredicate<T, U> / BiConsumer<T, U>

test / accept

Two-input versions

UnaryOperator<T>

apply(T t)

A Function where input and output are the same type

BinaryOperator<T>

apply(T a, T b)

A BiFunction where both inputs and the output are the same type

Let's try them all:

import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
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;

class Main {
    public static void main(String[] args) {

        Predicate<Integer> isEven = n -> n % 2 == 0;
        System.out.println(isEven.test(10));

        Function<String, Integer> length = s -> s.length();
        System.out.println(length.apply("Java"));

        Consumer<String> shout = s -> System.out.println(s.toUpperCase());
        shout.accept("hello");

        Supplier<String> defaultName = () -> "Guest";
        System.out.println(defaultName.get());

        UnaryOperator<Integer> square = n -> n * n;
        System.out.println(square.apply(7));

        BinaryOperator<Integer> max = (a, b) -> a > b ? a : b;
        System.out.println(max.apply(12, 30));

        BiFunction<String, Integer, String> repeat = (s, times) -> s.repeat(times);
        System.out.println(repeat.apply("ab", 3));
    }
}

Output:

true
4
HELLO
Guest
49
30
ababab

A common beginner mistake is calling the wrong method name. Remember: Predicate → test(), Function → apply(), Consumer → accept(), Supplier → get().

Passing Behaviour to Your Own Methods

The real power appears when we write methods that accept these interfaces. Here, one filter() method can keep elements by any rule, and one transform() method can convert elements in any way:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

class Main {

    static List<Integer> filter(List<Integer> numbers, Predicate<Integer> rule) {
        List<Integer> result = new ArrayList<>();
        for (int n : numbers) {
            if (rule.test(n)) {
                result.add(n);
            }
        }
        return result;
    }

    static List<String> transform(List<Integer> numbers, Function<Integer, String> mapper) {
        List<String> result = new ArrayList<>();
        for (int n : numbers) {
            result.add(mapper.apply(n));
        }
        return result;
    }

    public static void main(String[] args) {

        List<Integer> marks = List.of(85, 32, 91, 45, 28, 67);

        System.out.println(filter(marks, m -> m >= 40));
        System.out.println(filter(marks, m -> m >= 80));
        System.out.println(transform(marks, m -> m >= 40 ? "Pass" : "Fail"));
    }
}

Output:

[85, 91, 45, 67]
[85, 91]
[Pass, Fail, Pass, Pass, Fail, Pass]

We wrote the looping logic once and reused it with different rules. The Stream API, which you will learn soon, is built on exactly this idea: its filter() method takes a Predicate and its map() method takes a Function.

Combining Functional Interfaces

Many built-in functional interfaces have default methods that combine small pieces of behaviour into bigger ones:

import java.util.function.Function;
import java.util.function.Predicate;

class Main {
    public static void main(String[] args) {

        Predicate<Integer> isEven = n -> n % 2 == 0;
        Predicate<Integer> isPositive = n -> n > 0;

        Predicate<Integer> evenAndPositive = isEven.and(isPositive);
        Predicate<Integer> evenOrPositive = isEven.or(isPositive);
        Predicate<Integer> isOdd = isEven.negate();

        System.out.println(evenAndPositive.test(-4));
        System.out.println(evenOrPositive.test(-4));
        System.out.println(isOdd.test(7));

        Function<Integer, Integer> addTen = n -> n + 10;
        Function<Integer, Integer> doubleIt = n -> n * 2;

        System.out.println(addTen.andThen(doubleIt).apply(5));
        System.out.println(addTen.compose(doubleIt).apply(5));
    }
}

Output:

false
true
true
30
20

Pay attention to the last two lines, because they are often confused:

addTen.andThen(doubleIt)  → first addTen, then doubleIt:  (5 + 10) * 2 = 30
addTen.compose(doubleIt)  → first doubleIt, then addTen:  (5 * 2) + 10 = 20

Primitive Specialisations

Generic interfaces like Predicate<Integer> work with wrapper objects, so every int is autoboxed into an Integer. For performance-sensitive code, java.util.function also offers versions that work directly with primitives:

IntPredicate        test(int)          → boolean
IntFunction<R>      apply(int)         → R
IntUnaryOperator    applyAsInt(int)    → int
IntBinaryOperator   applyAsInt(int, int) → int
IntConsumer, IntSupplier, ...
(and the same family for long and double)

For example:

IntBinaryOperator add = (x, y) -> x + y;
System.out.println(add.applyAsInt(3, 4));   // 7, no boxing involved

You don't need to memorise these. Just know that they exist and avoid boxing when working with large amounts of numeric data.

Which Interface Should I Use?

Need to check something (yes/no)?          → Predicate
Need to turn an A into a B?                → Function
Need to do something, returning nothing?   → Consumer
Need to create or provide a value?         → Supplier
Need to compare two objects for sorting?   → Comparator
Need a task to run (e.g. on a thread)?     → Runnable

Create your own functional interface only when none of the built-in ones fits well, or when a descriptive name (like PaymentValidator) makes your code much clearer.

The Main Idea

A functional interface has exactly one abstract method, so an object of that interface represents a single piece of behaviour that can be passed to methods, stored in variables, and combined.

Key points to remember:

  • Default methods, static methods, and Object methods don't count towards the "one abstract method" rule.

  • @FunctionalInterface is optional, but it makes the compiler check the rule.

  • The core built-in interfaces are Predicate, Function, Consumer, and Supplier.

  • Functional interfaces can be implemented by a class, an anonymous class, or a lambda expression.

A favourite interview question is: "Can a functional interface have more than one method?" Yes. It can have many default and static methods, but only one abstract method. In the next chapter, you will learn lambda expressions properly, the most common way of implementing functional interfaces.