Volume 3 Exercises: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Exercises: The Backend

V3·37

Functional Programming

Exercises for Volume 3, chapter 37: what makes programming functional; map, filter and fold; functional interfaces, lambdas, closures, method references and composition; streams, laziness, flatMap, mapMulti and collectors; Optional and other maybe types; monads in plain words; side effects, parallel streams and stream performance; recursion and tail calls; and functional style in a Spring service, with Python, Go and Rust for comparison. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The four sets and the locking work as before. The code is Java 21, with Python, Go 1.24 and Rust 1.97 for comparison. Every quoted output is real.

Six of the measured outputs surprise experienced developers:

  • P1. groupingBy over no matches returned {}, while partitioningBy returned {false=[], true=[]}. toMap with a null value threw NullPointerException.
  • P2. Optional.orElse(expensive()) ran expensive even though the value was present. orElseGet didn't.
  • P3. A method reference s::length on a null s threw when it was created. The equivalent lambda was created fine.
  • P4. List.of(1,2,3).stream().peek(...).count() returned 3, but peek ran 0 times. After a filter, it ran 3 times.
  • P6. Recursive sum threw StackOverflowError at n = 10,000 with a 512 KB stack. The default main-thread stack went about 10,700 frames deep.
  • P9. Rust's iterator chain and its hand-written loop took the same time (73.9 ms and 72.1 ms for 50 million elements).

The chapter's lab, which the exercises build on rather than repeat, measured:

  • a parallel forEach into an ArrayList keeping 728,726 of 1,000,000 elements;
  • Stream<Integer> taking 595.6 ms against 6.8 ms for IntStream, while reduce(0, Integer::sum) silently overflowed;
  • parallel streams being slower for cheap work and 2.0× faster on 2 cores for heavy work;
  • laziness touching exactly 21 elements of an infinite stream;
  • a reused stream throwing.

TiffinBox's orders and reports are the running example.

Coverage map.

Chapter component Exercises
what makes programming functional; map/filter/fold T1, P1
functional interfaces; lambdas and closures T2, P3
method references; composition T2, P3
streams: what they are; laziness T3, P4
laziness in other languages T3, P9
flatMap and mapMulti T4, P5
collectors (grouping, partitioning, toMap, teeing) T4, P1, P5
Optional and maybe types T5, P2
monads in plain words T5
side effects in pipelines; parallel streams T6, P7
stream performance pitfalls T7, P7
recursion and tail calls T8, P6
checked exceptions and lambdas T2, P8
functional style in a Spring service T9, P8

Theory

T1. What makes programming functional

  1. Define the core ideas: pure functions, immutability, first-class functions, expressions over statements, and composition. Which of them does Java support well (records, lambdas, streams, final), which only partly (no persistent collections, checked exceptions), and which not at all (tail calls, ch37's P6)?
  2. Express map, filter and fold in their own terms. Show that filter and map can both be written with fold (reduce), and explain why Java's three-argument reduce(identity, accumulator, combiner) exists. What do associativity and the identity element have to do with parallel streams?
  3. List the concrete benefits a backend gets from functional style: testable pricing rules, safe concurrency (ch38), and reproducible reports. Then the costs: debugging pipelines, allocation, and a team unfamiliar with the style. Where should TiffinBox draw the line?

T2. Functional interfaces, lambdas, closures and method references

  1. A functional interface is an interface with one abstract method; the java.util.function families are Function, BiFunction, Supplier, Consumer, Predicate, UnaryOperator and BinaryOperator, plus the primitive variants IntFunction, ToLongFunction and the rest. When should you define your own (PricingRule, Clock), and what does @FunctionalInterface add?
  2. Closures. A lambda can capture only effectively final local variables (P3 captured a per-iteration copy j and printed 012), but it can capture and mutate the objects those variables refer to (the lab's ArrayList mutated from a parallel stream). Explain why Java made this choice, how it compares with JavaScript closures over let and var (Volume 2), and where this points inside a lambda compared with an anonymous class.
  3. Method references come in four kinds: static (Integer::parseInt), bound (s::length), unbound (String::length) and constructor (ArrayList::new). P3 showed that s::length evaluates s when the reference is created, so a null s threw immediately, while () -> s.length() evaluates it on each call. Explain the difference, and why andThen and compose gave 12 and 11 for plus1 and times2 on 5.

T3. Streams and laziness

  1. A stream is not a collection. It's a one-shot pipeline: a source, then lazy intermediate operations, then one terminal operation. Reusing one throws (the lab's "stream has already been operated upon or closed"). Explain stream characteristics (SIZED, SORTED, DISTINCT, ORDERED) and how they let the JDK skip work. The lab's sorted() on an already-sorted range was skipped; P4's peek didn't run with count() on a SIZED source.
  2. Laziness and short-circuiting. The lab touched 21 elements of an infinite stream. Python's generator (P9: [7, 14, 21], touched 21) and Go 1.23's range-over-func iterator (P9: touched 21) behave the same way. Compare them with Rust's iterators (zero-cost: P9's chain took 73.9 ms against 72.1 ms for the loop), Kotlin sequences, and JavaScript iterator helpers.
  3. Why is it wrong to rely on side effects in peek, map or filter? Use P4 (peek skipped for count()), the lab (sorted() skipped) and the JDK's freedom to fuse, reorder or elide operations.

T4. flatMap, mapMulti and collectors

  1. flatMap maps each element to a stream and concatenates the results: order lines from orders, add-ons from lines, and Optional::stream to drop empties (P5: [a, b]). mapMulti (JDK 16) pushes zero or more results into a sink (P5 split "idli,vada" and "dosa" into [idli, vada, dosa]). When is mapMulti better?
  2. Collectors. Explain toList/toSet/toMap (duplicates and nulls: ch35's P8 duplicate-key message; P1's null-value NPE), groupingBy with downstream collectors and map factories (P5: {Asha=9500, Ravi=6000} in a TreeMap), partitioningBy, counting, summingLong, mapping, filtering, flatMapping, collectingAndThen, teeing (P5: average paise 5166) and joining.
  3. The empty case. P1's groupingBy over no matches gave {}, while partitioningBy gave both keys with empty lists. Why does this matter for APIs and dashboards (missing keys against zero counts), and how do you produce a complete report with zeros (an EnumMap pre-filled for every status, ch35)?

T5. Optional, maybe types and monads in plain words

  1. Optional is for return values that may be absent. List the misuses: - Optional fields and parameters; - Optional.get() without a check; - Optional<List<T>> instead of an empty list; - isPresent() followed by get(); - Optional.of(nullable) (P2: NPE); - orElse(expensive()) (P2: ran even when the value was present).

Write the idiomatic alternatives. 2. Compare maybe types: Kotlin's T? with ?. and ?:, Rust's Option<T> with ? and combinators, Haskell's Maybe, TypeScript's T | undefined with ?. and ??, and Go's (T, bool) with zero values. Which ones are enforced by the compiler? 3. Explain monads in plain words. A monad is a "box" with map (transform the content) and flatMap (chain an operation that returns another box), plus a way to put a value in. Optional, Stream, CompletableFuture (thenCompose) and ch36's Result all fit this shape. What problem does flatMap solve that map doesn't, and what do the monad laws guarantee?

T6. Side effects and parallel streams

  1. The lab's parallel forEach into an ArrayList kept 728,726 of 1,000,000 elements, while toList kept all of them. Explain why collectors are correct in parallel (a container per thread, then merge) and list the side effects that make a parallel pipeline wrong: shared mutable collections, counters, non-thread-safe SimpleDateFormat or Random, and I/O order.
  2. When are parallel streams appropriate in a backend? Consider the lab (2.0× faster for 2 million heavy items, slower for 1,000 cheap ones), the shared common ForkJoinPool competing with every request, blocking I/O inside parallel streams, splittable sources, and forEachOrdered.
  3. Even sequential pipelines with side effects mislead readers. A sequential forEach that merged into an external HashMap worked, and so did the collector version (both gave {Asha=2, Ravi=1}, measured on JDK 21). Which one should you write, and why?

T7. Stream performance pitfalls

  1. Explain the lab's results: Stream<Integer> took 595.6 ms, IntStream 6.8 ms and a for loop 10.7 ms, and reduce(0, Integer::sum) silently overflowed to −1009630016. List the boxing traps (map instead of mapToLong, Collectors.summingInt over large values, boxed(), Stream.iterate with boxed seeds) and their fixes.
  2. Other performance pitfalls: - sorted() and distinct() buffering everything (the lab's 1,000 elements touched); - stream().filter().findFirst() as an id lookup in a loop (ch35's lookups); - Collectors.toMap resizing without presizing; - flatMap creating many small streams (T4); - lambdas capturing large objects; - Stream.of(array) versus Arrays.stream.
  3. How do you measure stream code properly? Cover JMH, warm-up, the dead-code trap, and allocation profiling with -prof gc and JFR. When is a plain loop the better choice?

T8. Recursion and tail calls

  1. P6 showed that recursive sum(10,000) overflowed a 512 KB stack. The default main-thread stack reached about 10,700 frames, and a thread with a 64 MB stack reached about 1.67 million. Python stopped at its recursion limit of 1,000 ("maximum recursion depth exceeded"). Explain stack frames, why the JVM doesn't eliminate tail calls, and how Scala (@tailrec), Kotlin (tailrec), Clojure (recur) and some functional languages handle it.
  2. Show four ways to make deep recursion safe in Java: rewriting as a loop or fold (P6's LongStream.rangeClosed(1, 100000).sum() gave 5000050000), an explicit stack (for tree traversal), trampolines, and bounding the depth. Which fits a menu category tree, a JSON document from an untrusted client, and a dependency graph?
  3. Recursion in backend code: when is it the clearest form (tree-shaped data, parsers, divide and conquer), and what limits must protect it?

T9. Functional style in a Spring service

  1. Structure a TiffinBox use case, "place order", as functional core, imperative shell. - Pure functions: validate(cart, menu, now), price(cart, rules) and toOrder(...). Each returns values or Result. - The service method: loads data, calls the pure core, saves, and publishes events inside a transaction.

Why does this make testing and reasoning easier? 2. Where do lambdas and streams appear naturally in Spring: Optional from repositories, ResponseEntity mapping, RestClient responses, Reactor's Mono/Flux (ch48), configuration of beans as functions (RouterFunction), and transactional templates. What goes wrong when lambdas cross transaction or proxy boundaries (lazy loading inside streams after the transaction closed, @Transactional on a lambda-called private method)? 3. Checked exceptions in lambdas: P8's Files.readString in map failed with "unreported exception IOException; must be caught or declared to be thrown". Compare the options: wrap the call in an unchecked exception, use a helper unchecked(ThrowingFunction), use a Result, or use a loop.

Programming exercises

P1. Map, filter, fold and the empty case

Using TiffinBox orders, compute: - revenue per kitchen; - ready orders per kitchen; - the most expensive order; - the average order value.

Do each three ways: with reduce, with collectors, and with a loop. Then run everything on an empty list and on a list with no matches. Show groupingBy's {} against partitioningBy's two keys, and toMap's NPE on a null value, and fix them so the report always lists every kitchen and status.

P2. Optional done right

Show these behaviours and count how often a default is computed: - orElse against orElseGet when the value is present; - Optional.of(null) against ofNullable; - a chain using map and flatMap: customer → default address → serviceable kitchen.

Then refactor a method that uses isPresent/get, Optional parameters and Optional<List<…>> into idiomatic code.

P3. Closures, method references and composition

Demonstrate: - per-iteration capture (012); - a bound method reference on null throwing at creation, against a lambda; - andThen against compose (12 and 11); - Predicate composition for a menu filter (veg and under ₹100 and not sold out); - a Comparator pipeline.

Then build a PricingRule pipeline from a list of UnaryOperator<Money> using reduce(UnaryOperator.identity(), …).

P4. Laziness and characteristics

Show these, and explain each: - peek not running for count() on a sized source, but running after filter; - the lab's sorted() being skipped on a sorted range; - an infinite stream with limit; - reusing a stream throwing; - Supplier<Stream<T>> as the fix.

Finally, replace a "debug counter in map" with a correct metric.

P5. Collectors toolkit

Build a kitchen report in one pass per question: - revenue by kitchen in a TreeMap; - dishes per kitchen as sets (mapping); - expensive orders per kitchen (filtering, counting); - average and count together (teeing); - add-ons flattened from lines (flatMap against mapMulti); - a comma-joined summary.

Compare Stream.toList() with Collectors.toList() for mutability.

P6. Recursion limits and safe alternatives

Measure: - the recursion depth with the default stack; - with a 512 KB stack; - with a thread given 64 MB; - in Python.

Then rewrite these three recursive functions iteratively: - sum(n); - a menu tree flattening (explicit stack); - a nested JSON depth check with a limit.

Show that Jackson rejects JSON nested deeper than its limit.

P7. Parallel streams: when and when not

Reproduce the lab's lost elements with parallel().forEach(list::add) and fix it with a collector. Then measure, on this machine: - parallel against sequential for cheap and expensive work; - a parallel stream doing Thread.sleep(10) per element (simulated blocking I/O) on the common pool, while other CompletableFuture.supplyAsync tasks wait.

Write the team rule.

P8. Checked exceptions and functional style in a service

Show the compile error for Files.readString inside map. Then implement an import that reads 100 menu files, parses each one, and reports per-file failures, four ways: - wrapping in UncheckedIOException; - a ThrowingFunction helper; - Result per file; - a loop.

Then structure "place order" as functional core and imperative shell, with tests for the core that need no mocks.

P9. Laziness and pipelines in other languages

Implement "first 3 multiples of 7 from an infinite source" in: - Python (generator plus islice); - Go 1.23 (range-over-func iterator); - Rust (iterator chain); - JavaScript (a generator, or iterator helpers in Node 22).

Count the elements touched in each. Then benchmark Rust's iterator chain against a loop over 50 million elements, and compare with the lab's Java numbers.

Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–37)

C1. A pure pricing and checkout core

Build TiffinBox's checkout core as pure functions: - validate(cart, menu, now) → Validation<ValidCart> (ch36's C1); - price(validCart, rules) → PricedCart with an explanation trail (ch34's C2); - split(priced, ways) (ch33's P3).

Rules are UnaryOperator-style functions composed from configuration. Give it 100% branch coverage with table tests, plus jqwik properties: - totals are never negative; - the order of commutative rules doesn't matter; - applying zero rules is the identity.

Combines: Volume 1's testing, Volume 2's frontend pricing parity (ch33's P2), ch33's money, ch34's composition, ch36's Result, and this chapter.

C2. A streaming daily report job

Write the nightly job that reads 2 million order rows (CSV or JDBC, streamed rather than loaded), computes per-kitchen totals, per-status counts with zeros, top-10 dishes and hourly histograms in one pass with collectors, and writes deterministic JSON (ch35's C3). Measure the memory and the time, use primitive streams where possible, and compare with a loop version.

Combines: Volume 1's file and stream I/O, Volume 2's dashboards (ch32), ch35's collections and determinism, and this chapter's collectors and performance rules.

C3. Port a pipeline to the frontend and back

TiffinBox's kitchen dashboard (Volume 2 ch25) computes "orders per status" in TypeScript, while the backend computes the same for the API. Write both versions with the same semantics (empty statuses as zeros, the same rounding for averages, the same ordering), generate shared fixtures, and run the fixtures in both test suites. Note which functional idioms translate directly (map, filter, reduce) and which differ (TypeScript's lack of lazy streams, Java's collectors).

Combines: Volume 2's state management and testing (ch25, ch26), ch35's determinism, and this chapter.

What the chapter leaves out

Gatherers (JDK 24)

JEP 485 (final in JDK 24) adds Stream.gather(Gatherer), user-defined intermediate operations, much as collectors are user-defined terminal operations. The built-in Gatherers.windowFixed(3), windowSliding(3), fold, scan and mapConcurrent(n, f) cover sliding averages, running totals, batching and bounded concurrent mapping (with virtual threads). Before gatherers, these needed custom spliterators or loops. Chapter 39 (Modern Java) covers it; on JDK 21 you can't use it yet.

Reactive streams and backpressure

Java streams are pull-based and synchronous. Reactive streams (Flow in the JDK, Project Reactor's Flux/Mono, RxJava) are push-based and asynchronous, with backpressure: consumers signal how much they can handle. That suits streaming HTTP, message consumption and WebFlux (ch48). The same functional vocabulary (map, filter, flatMap) applies, but flatMap there means concurrent subscription, and errors and cancellation are part of the stream. Learn the differences before mixing the two.

Persistent data structures and lenses

Updating nested immutable records (order.withCustomer(order.customer().withAddress(…))) gets verbose. Functional languages use lenses or optics; Java has record withers (proposed derived record creation, JEP 468) and builders. For deep updates, restructure the data (flatter records, ids instead of nesting) or write small update functions. Persistent collections (ch35's T9) complement immutable records.

Effect systems and functional architecture

Beyond "functional core, imperative shell", languages and libraries model effects explicitly. Haskell's IO, Scala's ZIO and Cats Effect, and Kotlin's Arrow make effects values that can be composed, retried and tested. In Java, the same ideas appear in CompletableFuture, Reactor, structured concurrency (ch38) and resilience decorators (ch52). Knowing the concept helps you read those libraries' designs.

Memoisation and laziness for values

Supplier memoisation runs an expensive computation once on first use. The tools are Guava's Suppliers.memoize, a holder-class idiom, or the Stable Values / lazy constants JEP (preview in recent JDKs). It's useful for configuration and expensive caches computed from immutable inputs. Thread-safety matters here (ch38's safe publication). Use ConcurrentHashMap.computeIfAbsent for keyed memoisation (ch35's T8 pitfalls apply).

Senior exercises

S1. Functional-style guidelines for the team

Write one page saying: - when to use streams against loops; - Optional rules; - collector rules (including empty-case handling); - the side-effect policy; - the parallel stream policy; - primitive streams for numbers; - checked exception handling; - functional core and imperative shell.

Tie each rule to an output from this chapter, and name the check that enforces it.

S2. Review a stream-heavy pull request

A PR replaces a 40-line loop in the settlement job with this one expression:

Java
orders.parallelStream().filter(o -> { log.info("checking {}", o.id()); return o.isSettled(); })
  .map(o -> o.getTotal())
  .reduce(0, Integer::sum)

It also adds Optional<Kitchen> kitchen as a field on Order and repo.findDefault().orElse(repo.createDefault()) in the setup, and it collects Collectors.toMap(Order::kitchenId, Order::getTotal) into a map that later code mutates. Write the review.

S3. Decide between streams, loops and Reactor for a new feature

TiffinBox needs a "live kitchen load" feature: consume order events from a message broker (ch51), compute a rolling 5-minute load per kitchen, and push updates to dashboards over SSE (Volume 2 ch19). Options: - Java streams over polled batches; - plain loops with a scheduled executor; - Project Reactor end to end (Flux from the broker, windowing, SSE); - virtual threads with blocking code (ch38).

Decide, and justify.

S4. Teach the five functional traps

Prepare a 20-minute session using five outputs: - orElse running its argument (P2); - peek skipped for count() (P4); - the parallel forEach losing 271,274 elements (the lab); - the Integer reduce overflowing (the lab); - groupingBy returning {} for no matches (P1).

For each, show the code, take a prediction, reveal, explain in one sentence, and give the fix.

S5. Plan the adoption of functional core / imperative shell across a codebase

TiffinBox's order service has 15,000 lines with business rules spread through controllers, JPA entity listeners and service methods mixing I/O and logic, and its tests rely on heavy mocking (Mockito stubs on every repository). Plan a 3-month migration to a functional core with an imperative shell. Cover: how to find the rules, how to extract them safely, how tests change, how to measure progress, and how to stop regressions.