Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 09 / Topic 6 of 10

Lambdas and functional interfaces

A functional interface is an interface with exactly one abstract method. A lambda expression is a short way to write an object that implements that one method, without a named class.

@FunctionalInterface
interface DiscountRule {
    double apply(double amount);
}

DiscountRule festiveTenPercent = amount -> amount * 0.90;
System.out.println(festiveTenPercent.apply(2499.0));   // 2249.1

@FunctionalInterface is optional, but it asks the compiler to check the "exactly one abstract method" rule for you, so a careless second method added later fails to compile instead of silently breaking every lambda that implements the interface.

You rarely need to write your own functional interface, because java.util.function already ships the common shapes:

Interface Method Takes Returns Typical use
Predicate<T> test(T) one value boolean a yes/no check, e.g. for filter
Function<T, R> apply(T) one value another value transform a value, e.g. for map
BiFunction<T, U, R> apply(T, U) two values a value combine two values into one
Supplier<T> get() nothing a value produce a value lazily, on demand
Consumer<T> accept(T) one value nothing a side effect, e.g. for forEach
UnaryOperator<T> apply(T) one value the same type a Function<T, T>, e.g. String::toUpperCase

Real-world example: a shop's orders, filtered and transformed with these interfaces.

Predicate<Order> isPune = order -> order.city().equals("Pune");
Predicate<Order> isBig = order -> order.amount() >= 1000;
orders.stream().filter(isPune.and(isBig)).map(Order::id).toList();
Pune AND big: [ORD-1001, ORD-1003]
Pune OR big:  [ORD-1001, ORD-1002, ORD-1003]
NOT Pune:     [ORD-1002, ORD-1004]

Predicate can be combined with .and(...), .or(...) and .negate() instead of writing a bigger lambda by hand; Function composes the same way with .andThen(...) (run this, then that) and .compose(...) (run that first, then this).

Function<Double, Double> applyGst = amount -> amount * 1.18;
Function<Double, Long> gstThenRound = applyGst.andThen(Math::round);
System.out.println(gstThenRound.apply(2499.0));   // 2949

A Supplier builds nothing until .get() is called — this is what makes orElseGet in section 9 different from orElse.

Full program: examples/FunctionalInterfaces.java.

Done here? The practice set for Part 9 — including the solutions — is on the part page.

Search the guide