Skip to the page

Types, errors and modern syntax · core

Lambdas, functional interfaces and Optional

A lambda supplies the one abstract method of a functional interface. Lambdas capture values, not variables. Optional is for return values, not for fields.

The notes

What you must know

  • A functional interface has exactly one abstract method. @FunctionalInterface is optional but makes the compiler check it.
  • Built-ins: Function, BiFunction, Supplier (no input), Consumer (no output), Predicate (boolean), UnaryOperator, BinaryOperator.
  • Comparator counts as functional: compare is its only abstract method.
  • Lambdas capture values, not variables. A local variable might be gone or changed by another thread when the lambda runs, so it must be effectively final.
  • Inside a lambda this is the enclosing object. Inside an anonymous class it is the anonymous object.
  • Checked exceptions in lambdas: catch and wrap (UncheckedIOException), or use a loop.
  • Optional: orElse(x) evaluates x every time, even when a value exists. Use orElseGet(() -> ...) for expensive defaults. orElseThrow(...) replaces get().
  • Do not use Optional as a field or parameter: it is not Serializable, the field can still be null, and it confuses JSON and JPA mappers. Never return null from a method that returns Optional. Optional.of(null) throws; use ofNullable. isPresent() followed by get() is a sign to use map, flatMap or orElseThrow.

The red pen

Common traps: mistake → fix

  • Mistake: orElse(call()) calls call() only when empty

    Fix: the argument is always evaluated; use orElseGet.

  • Mistake: A lambda can change a local counter

    Fix: locals must be effectively final; use a stream operation or an atomic.

  • Mistake: Optional fields are good style

    Fix: use Optional for return values only.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a functional interface?
  2. Why must a variable used in a lambda be effectively final?
  3. What is wrong with repo.findById(id).get()?
  4. Difference between orElse and orElseGet?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview