Lambdas & Functional Interfaces

Lambdas & Functional Interfaces in Java: A lambda is a function you can pass around as a value.

Concept Explanation

A lambda is a function you can pass around as a value. It replaced the anonymous inner class, which required six lines of ceremony to express one line of logic.

// Before Java 8
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println("Clicked");
    }
});

// With a lambda
button.addActionListener(e -> System.out.println("Clicked"));

Functional Interfaces

A lambda can implement any interface with exactly one abstract method. @FunctionalInterface documents and enforces that:

@FunctionalInterface
public interface Validator<T> {
    boolean validate(T value);          // exactly one abstract method
}
Validator<String> notBlank = s -> s != null && !s.isBlank();

The Built-In Set

You rarely need your own — java.util.function covers most shapes:

InterfaceSignatureUse
Predicate<T>T → booleanfiltering
Function<T,R>T → Rtransforming
Consumer<T>T → voidside effects
Supplier<T>() → Tlazy creation
UnaryOperator<T>T → Tsame-type transform
BiFunction<T,U,R>(T,U) → Rtwo inputs
Predicate<String> isLong  = s -> s.length() > 10;
Function<String, Integer> length = String::length;
Consumer<String> print    = System.out::println;
Supplier<List<String>> newList = ArrayList::new;
BiFunction<Integer, Integer, Integer> add = Integer::sum;

Composition

These interfaces combine, which is where they earn their keep:

Predicate<String> notEmpty = s -> !s.isEmpty();
Predicate<String> shortEnough = s -> s.length() < 20;

Predicate<String> valid = notEmpty.and(shortEnough);
Predicate<String> invalid = valid.negate();

Function<String, String> trim = String::trim;
Function<String, String> upper = String::toUpperCase;
Function<String, String> clean = trim.andThen(upper);   // trim, then upper

Method References

Four forms, all shorthand for a lambda:

String::toUpperCase        // instance method of the parameter
System.out::println        // instance method of a specific object
Integer::parseInt          // static method
ArrayList::new             // constructor

Prefer them when the lambda body is a single call — String::length reads better than s -> s.length().


Passing Behaviour as a Parameter

The pattern that lambdas enable everywhere:

public <T> List<T> retry(int attempts, Supplier<T> action) {
    for (int i = 0; i < attempts; i++) {
        try { return List.of(action.get()); }
        catch (Exception e) { if (i == attempts - 1) throw e; }
    }
    return List.of();
}

// Caller supplies the behaviour
User u = retry(3, () -> client.fetchUser(id)).get(0);

Common Mistakes

  1. Mutating a captured variable: Lambdas capture effectively final values. Use an AtomicInteger or a stream collector for accumulation.
  2. Checked exceptions inside a lambda: The built-in interfaces do not declare them. Wrap in a try/catch or write your own interface that throws.
  3. Multi-line lambdas: Once it needs braces and three statements, extract it to a named method.
  4. this confusion: In a lambda, this refers to the enclosing instance — unlike in an anonymous class. This is usually what you want.

Best Practices

  • Method references over lambdas when the body is one call.
  • Reuse the built-in functional interfaces rather than declaring your own.
  • Keep lambdas to one expression; extract anything longer.
  • Name predicates when reused: Predicate<Order> isPaid = ... documents the rule and can be composed.

Practice Exercises

  1. The Composition: Build three Predicate<String> rules and combine them with and, or, and negate.
  2. The Retry: Implement the retry(int, Supplier<T>) method above and use it on a method that fails twice before succeeding.
  3. The Four References: Write one example each of the four method-reference forms and the equivalent lambda.