🎯 What you will learn
Before Java 8, passing behaviour meant writing anonymous inner classes — verbose and noisy. Lambdas collapse them to a single expression. By the end of this lesson you will understand:
- Lambda syntax:
(params) -> expressionor(params) -> { block; } - The four core functional interfaces:
Predicate,Function,Consumer,Supplier - Composing predicates with
and,or,negate - Composing functions with
andThenandcompose - Four forms of method references (
::) - Capturing effectively-final variables
💳 Real-world scenario
BoraPay processes thousands of mixed-method transactions daily — UPI, Card, Net Banking. Wanjiku needs to sort them by amount, flag high-value transfers for compliance review, mask card numbers for display, and convert KES amounts through a fee-deduction → USD pipeline. Lambdas and composed functions make each step composable and testable in isolation.
λ Lambda basics — Predicate, Function, Comparator
A lambda is an anonymous implementation of a functional interface — any interface with exactly one abstract method. The compiler infers which interface you mean from context.
Lambda capture rule: A lambda can read local variables from the enclosing scope only if they are effectively final — never reassigned after their initial assignment. Instance fields and static fields have no such restriction.
:: Method references — four forms
A method reference is shorthand for a lambda that only calls a single existing method. There are four forms: static, instance on a specific object, instance on an arbitrary instance of a type, and constructor.
⚙️ Functional composition
Function.andThen(g) chains f then g — left-to-right, like a data pipeline. Predicate.negate(), and(), or() build Boolean logic without if trees. UnaryOperator<T> is shorthand for Function<T,T>.
📋 Quick reference — functional interfaces
| Interface | Method | Description |
|---|---|---|
Predicate<T> | test(T)→boolean | Filter condition |
Function<T,R> | apply(T)→R | Transform T to R |
Consumer<T> | accept(T)→void | Side effect on T |
Supplier<T> | get()→T | Produce a T |
BiFunction<T,U,R> | apply(T,U)→R | Two inputs, one output |
UnaryOperator<T> | apply(T)→T | Function<T,T> shorthand |
Comparator<T> | compare(T,T)→int | Ordering |
🧩 Mini challenge
Create a Function<Double, Double> that applies a 10% BoraPay loyalty discount, then converts KES to USD at 132.50, then rounds to 2 decimal places using andThen. Apply it to 20,000 KES and print the result.
Given a list of transaction strings like "CARD-45000", write three Predicates: isCard, isHighValue (>= 10,000), and cardHighValue using and(). Filter and print the matching transactions.
Define a simple Transaction record with String method and double amount. Use a BiFunction<String, Double, Transaction> constructor reference to build three Transaction objects from parallel lists of methods and amounts. Print them.
🎤 Interview Q&A
An interface with exactly one abstract method. The @FunctionalInterface annotation enforces this at compile time (optional but recommended). Runnable, Callable, Comparator, Predicate, Function, Consumer, Supplier are all functional interfaces. A lambda expression is syntactic sugar for an anonymous class implementing the single abstract method.
map and flatMap on a Stream?map transforms each element to exactly one element — 1-to-1. flatMap transforms each element to a Stream of elements and then flattens all those streams into one — 1-to-many. Example: stream.map(s -> s.split(",")) gives a Stream of arrays; stream.flatMap(s -> Arrays.stream(s.split(","))) gives a flat Stream of Strings.
Lambdas may outlive the method that created them (e.g., stored in a field or passed to another thread). Local variables live on the stack and are gone when the method returns. To avoid referencing stale stack data, Java requires captured variables to be effectively final — their value is copied into the lambda's closure. Reassigning would make the copy stale or create race conditions in concurrent code.
Comparator.comparing() over a manual lambda comparator?Comparator.comparing(Person::getName) is cleaner, null-safe when combined with nullsFirst()/nullsLast(), and composable with .thenComparing(). A manual lambda is needed when the comparison logic is complex or involves multiple transformations. For simple field-based sorts, Comparator.comparing() is the idiomatic choice.
Function.andThen(g) and Function.compose(g).f.andThen(g) executes f first, then passes f's result to g — equivalent to g(f(x)). f.compose(g) executes g first, then passes g's result to f — equivalent to f(g(x)). andThen reads left-to-right (pipeline order); compose reads right-to-left (mathematical function composition). andThen is almost always clearer for data pipelines; compose is rarely used in practice.
📝 Quiz — 5 questions
(a, b) -> a + b most closely matches which functional interface?ClassName::staticMethod is what type of method reference?Predicate<String> p = s -> s.length() > 5; p.negate() returns what?Function.andThen(g) — what order do functions execute?Next: Streams API — filter, map, reduce →
⚠️ Common mistakes
String::toUpperCase is an instance method ref on an arbitrary instance; System.out::println is an instance ref on a specific instance (System.out). Mixing them up causes compiler type-mismatch errors.Comparator.comparing(Transaction::getAmount) throws NullPointerException if any amount is null. Use Comparator.comparing(t -> t.getAmount(), Comparator.nullsFirst(...)) for null safety.parallelStream() may run concurrently. Mutating a shared List or counter from inside a lambda causes race conditions. Use Collectors.toList() or atomic accumulators instead.✅ Key takeaways
- A lambda is a concise anonymous implementation of a
@FunctionalInterface. Predicatefilters,Functiontransforms,Consumerside-effects,Supplierproduces.- Method references (
::) are shorthand for single-method lambdas — four forms: static, instance-on-specific, instance-on-arbitrary, constructor. andThencomposes functions left-to-right;Predicate.and/or/negatecomposes predicates.- Captured local variables must be effectively final.
From lambdas to production Spring Boot
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →