🎯 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) -> expression or (params) -> { block; }
  • The four core functional interfaces: Predicate, Function, Consumer, Supplier
  • Composing predicates with and, or, negate
  • Composing functions with andThen and compose
  • Four forms of method references (::)
  • Capturing effectively-final variables
💼 Interview reality: "What is a functional interface?" and "explain method references" appear in almost every Java 8+ screening. Lambdas underpin the entire Streams API — this lesson is the foundation for Lesson 17.

💳 Real-world scenario

💳
Real-world scenario · BoraPay, Nairobi
Wanjiku builds a functional payment pipeline

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.

javac LambdaBasics.java && java LambdaBasics
LambdaBasics.javaLesson 16 · Predicate, Function, Comparator
verified output
=== BoraPay — Lambda Basics === Sorted by amount : [UPI-500, CARD-1200, UPI-2500, UPI-8000, CARD-18000, NETB-75000] High-value (>=5k): UPI-8000 CARD-18000 NETB-75000 Methods only : UPI CARD UPI UPI CARD NETB UPI + high-value : UPI-8000

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.

javac MethodRef.java && java MethodRef
MethodRef.javaLesson 16 · four method reference forms
verified output
=== BoraPay — Method References === Static ref : USD@132.5 100,000 KES = USD 754.72 Payment methods: -> M-PESA -> Card -> Bank Transfer -> QR Code Constructor ref: NGN@0.085

⚙️ 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>.

javac FunctionalCompose.java && java FunctionalCompose
FunctionalCompose.javaLesson 16 · andThen, negate, UnaryOperator
verified output
=== BoraPay — Functional Composition === KES amount After 1.5% fee USD equiv. -------------------------------------------- 10,000 9,850.00 74.34 50,000 49,250.00 371.70 150,000 147,750.00 1115.09 Transaction flags: KES 10,000 — small: true needs KYC: false KES 50,000 — small: false needs KYC: false KES 150,000 — small: false needs KYC: true Masked cards: ************4821 ************4444

📋 Quick reference — functional interfaces

InterfaceMethodDescription
Predicate<T>test(T)→booleanFilter condition
Function<T,R>apply(T)→RTransform T to R
Consumer<T>accept(T)→voidSide effect on T
Supplier<T>get()→TProduce a T
BiFunction<T,U,R>apply(T,U)→RTwo inputs, one output
UnaryOperator<T>apply(T)→TFunction<T,T> shorthand
Comparator<T>compare(T,T)→intOrdering

🧩 Mini challenge

Three lambda exercises
Task 1 — Compose a discount pipeline

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.

Task 2 — Predicate chain

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.

Task 3 — Constructor reference

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

EasyWhat is a functional interface?
+

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.

EasyWhat is the difference between 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.

MediumWhy can't lambdas reassign captured local variables from the enclosing scope?
+

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.

MediumWhen would you use 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.

HardExplain the difference between 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

Question 1 of 5
A lambda (a, b) -> a + b most closely matches which functional interface?
Question 2 of 5
ClassName::staticMethod is what type of method reference?
Question 3 of 5
Predicate<String> p = s -> s.length() > 5; p.negate() returns what?
Question 4 of 5
Function.andThen(g) — what order do functions execute?
Question 5 of 5
A local variable captured by a lambda must be:
0
/ 5
Quiz complete!

Next: Streams API — filter, map, reduce →

⚠️ Common mistakes

Capturing a non-effectively-final variable
A lambda can only capture local variables that are effectively final (never reassigned after being captured). Mutate a wrapper object or use an array of size 1 as a workaround.
Confusing method reference forms
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.
Forgetting Comparator.comparing() handles null poorly
Comparator.comparing(Transaction::getAmount) throws NullPointerException if any amount is null. Use Comparator.comparing(t -> t.getAmount(), Comparator.nullsFirst(...)) for null safety.
Lambda body modifying outer state in parallel streams
Lambdas in 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.
  • Predicate filters, Function transforms, Consumer side-effects, Supplier produces.
  • Method references (::) are shorthand for single-method lambdas — four forms: static, instance-on-specific, instance-on-arbitrary, constructor.
  • andThen composes functions left-to-right; Predicate.and/or/negate composes predicates.
  • Captured local variables must be effectively final.
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →