The BackendVol. 3 · Part III
0 / 0

Shelves / The Backend

BE·37

Functional Programming

Functions as values: functional interfaces, lambdas and closures, method references, composition, streams with their laziness and pipeline mechanics, collectors, Optional, parallel streams and their pitfalls. Built from first principles (purity, higher-order functions, map/filter/fold, monads in plain words) and compared with Rust iterators and closures, Go func values, C++ lambdas and ranges, Zig's explicit style, C# LINQ, Kotlin sequences, Python generators, Haskell and Elixir.

34 topics · ~37 min read · 32-question quiz
Updated Suggest a correction

Start here: functions as values, and pipelines of data

Two ideas

Functional programming rests on two ideas that every modern language has borrowed. First, functions are values: you can store a function in a variable, pass it to another function and return one. Second, prefer pure functions: ones whose result depends only on their inputs and which change nothing else, so they're easy to test, reuse and run in parallel. Java added both in Java 8 with lambdas and streams; Kotlin, C#, Scala, JavaScript, Rust and Python have their equivalents, and Haskell, OCaml, F#, Clojure and Elixir are built around them.

Functions are values

Java
Function<Integer, String> rupees = p -> "₹" + p / 100;
Predicate<Order> isPaid = Order::paid;                     // a method reference
Predicate<Order> isBig = o -> o.totalPaise() >= 10000;

rupees.apply(12000);
rupees.andThen(s -> s + " incl. GST").apply(4500);         // composing two functions
Text
a function used directly: ₹120 | composed: ₹45 incl. GST

Function<A, B>, Predicate<T> (returns a boolean), Supplier<T> (takes nothing), Consumer<T> (returns nothing) and BiFunction<A, B, C> are the standard functional interfaces in java.util.function; a lambda or a method reference (Order::paid) is just a compact way to create one. Functions compose: andThen, compose, and for predicates and, or and negate.

Loops versus streams

Here's the same question answered both ways: the total of paid orders of ₹100 or more.

Java
int sum = 0;
for (Order o : orders) if (o.paid() && o.totalPaise() >= 10000) sum += o.totalPaise();

int total = orders.stream().filter(isPaid.and(isBig)).mapToInt(Order::totalPaise).sum();
Text
paid orders of ₹100+: loop ₹570 | stream ₹570

A stream is a pipeline: a source (orders.stream()), any number of intermediate operations that each produce a new stream (filter keeps matching items, map transforms each one, sorted, distinct, limit), and one terminal operation that produces a result (sum, count, toList, collect, findFirst, forEach). The loop says how to compute the answer step by step; the stream says what the answer is. Neither is always better: streams shine for filtering, transforming and grouping, loops for complex control flow with early exits and several accumulators.

Grouping and the empty case

Java
Map<String, Integer> byCustomer = orders.stream().filter(Order::paid)
    .collect(Collectors.groupingBy(Order::customer, TreeMap::new, Collectors.summingInt(Order::totalPaise)));

Optional<Order> biggest = orders.stream().max(Comparator.comparingInt(Order::totalPaise));
orders.stream().filter(o -> o.customer().equals("Zoya")).findFirst().map(o -> "found").orElse("no order for Zoya");
Text
revenue by customer: {Asha=42000, Meena=8000, Ravi=15000}
biggest: order 3 | no order for Zoya

Collectors turn a stream into a collection or summary: toList, toSet, toMap, groupingBy, partitioningBy, joining, summingInt, counting. An operation that might find nothing, like max or findFirst, returns an Optional: a box that holds a value or is empty, which forces you to decide what happens when there's nothing (orElse, orElseThrow, map, ifPresent) instead of getting a NullPointerException later. Use Optional as a return type; don't use it for fields or parameters.

Streams are lazy

Java
Stream<Order> pipeline = orders.stream().filter(o -> { System.out.println("   checking order " + o.id()); return o.paid(); });
System.out.println("pipeline built, no checks yet; now findFirst():");
pipeline.findFirst();
Text
pipeline built, no checks yet; now findFirst():
   checking order 1
first paid: order 1

Building the pipeline did nothing; the terminal operation pulled elements through one at a time, and findFirst stopped after the first match. That's why streams can work on huge or even infinite sources, and why you shouldn't put side effects inside filter or map: whether and how often they run depends on the rest of the pipeline. A stream can be consumed once.

Purity

Java
Function<Integer, Integer> withTax = p -> p * 105 / 100;                                  // pure
Function<Integer, Integer> withTaxAndLog = p -> { log.add("taxed " + p); return p * 105 / 100; };   // side effect
Text
same input, same output: 1050 | hidden effect left behind: [taxed 1000, taxed 1000]

The pure version can be called any number of times, cached, tested with a single assertion and run on many threads at once. The impure one leaves state behind that depends on how often it ran, and the lab shows what happens when side effects meet parallel streams: a quarter of a million updates lost. Real programs need effects (databases, HTTP, logs); the functional style keeps them at the edges and the logic in the middle pure.

How deep to go in functional programming

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Write lambdas and method references; filter, map and collect with streams
L2 Use collectors, Optional and function composition; choose between loops and streams
L3 Explain laziness, purity, immutability, higher-order functions, and how Haskell, Scala, Clojure and Rust apply them
L4 Diagnose side effects in pipelines, unsafe parallel streams, boxing overhead and Optional misuse
L5 Structure a codebase with a functional core and imperative shell; decide when parallel streams pay
L6 Set functional-style conventions for a team that balance readability and performance

First principles

What makes programming "functional"

Functional programming (FP) is a style built on a few ideas, which languages support to varying degrees:

  1. Functions are values: they can be stored in variables, passed as arguments and returned from other functions (first-class functions). A function that takes or returns functions is a higher-order function.
  2. Pure functions: the result depends only on the arguments, and there are no side effects (no mutation of shared state, I/O, or exceptions as control flow). Pure functions are referentially transparent: a call can be replaced by its result without changing the program. This makes them trivially testable, cacheable (memoisation), parallelisable and reorderable.
  3. Immutable data (chapter 34): instead of changing values, you create new ones.
  4. Declarative composition: describe what to compute (orders.filter(paid).map(total).sum()) rather than how to loop.
  5. Expressions over statements and algebraic data types with pattern matching (chapters 33 and 39).

Real programs need effects (databases, HTTP, clocks). FP doesn't forbid them. It pushes them to the edges: a "functional core" of pure business logic, wrapped by an "imperative shell" that does the I/O. This architecture (Gary Bernhardt's Functional Core, Imperative Shell) works in any language, Java and Spring included.

Language First-class functions Purity enforced? Immutability default Laziness
Haskell Yes Yes (effects tracked in types: IO) Yes Lazy by default
Elixir/Erlang Yes No (but no shared mutable state) Yes Eager (Stream for lazy)
Scala, F#, OCaml, Clojure Yes No Mostly yes Eager with lazy options
Rust Yes (closures + Fn* traits) No (but mutation is explicit and controlled) Immutable bindings Lazy iterators
Kotlin Yes (function types) No val, read-only collections Sequence
Java Via functional interfaces (Java 8+) No No Streams are lazy
C# Delegates, lambdas No No LINQ is lazy (deferred execution)
Go func values, closures No No No (iterators since 1.23 are pull/push functions)
C++ Lambdas, std::function No (constexpr functions are pure-ish) No Ranges views are lazy
Zig Function pointers, no closures No const No
C Function pointers only No No No
Python Yes No No Generators

The core operations: map, filter, fold

Almost all collection processing reduces to three higher-order functions:

  • map (A → B): transform each element. [1,2,3].map(x → x*2) = [2,4,6].
  • filter (A → bool): keep elements that satisfy a predicate.
  • fold / reduce (B, A → B) with an initial B: combine all elements into one result. Sum, max, group-by and even map and filter can all be written as folds.
record Order(String customer, BigDecimal total, boolean paid) {}

BigDecimal revenue = orders.stream()
    .filter(Order::paid)                         // filter
    .map(Order::total)                           // map
    .reduce(BigDecimal.ZERO, BigDecimal::add);   // fold with identity

Functions as values in Java

Functional interfaces

Java has no function types. A lambda must target a functional interface: an interface with exactly one abstract method (a SAM type). @FunctionalInterface is optional documentation that makes the compiler reject a second abstract method. Default and static methods don't count.

The java.util.function package provides 43 standard interfaces. The core shapes:

Interface Signature Use
Function<T, R> R apply(T) Transform
BiFunction<T, U, R> R apply(T, U) Two inputs
UnaryOperator<T> / BinaryOperator<T> T apply(T) / T apply(T, T) Same-type transform / combine
Predicate<T> boolean test(T) Filter
Consumer<T> / BiConsumer<T,U> void accept(T) Side effect
Supplier<T> T get() Lazy value, factory
Primitive specialisations IntFunction<R>, ToIntFunction<T>, IntPredicate, IntUnaryOperator, IntBinaryOperator, LongSupplier, … Avoid boxing

Pre-existing SAM interfaces work too: Runnable, Callable<V>, Comparator<T>, and Spring's RowMapper<T> and TransactionCallback<T>.

Consequences of "interfaces, not function types":

  • There's no checked-exception-friendly standard interface (chapter 33). Define your own (ThrowingFunction<T, R, E extends Exception>) or wrap.
  • The combinatorial explosion of primitive specialisations exists because generics can't take primitives.
  • Two interfaces with identical shapes aren't interchangeable: a Predicate<String> isn't a Function<String, Boolean>. You adapt with a method reference (pred::test).
  • Kotlin, Scala, C#, Rust, Go, Swift and TypeScript have real function types ((T) -> R, Func<T, R>, impl Fn(T) -> R, func(T) R).

Lambdas and closures

A lambda expression is an anonymous function: (params) -> body. A closure is a function plus the variables it captures from its enclosing scope. How capture works is a real semantic difference between languages:

// Java captures VALUES of local variables, which must be effectively final (never reassigned).
int threshold = 100;
Predicate<Order> big = o -> o.total().intValue() > threshold;   // copies threshold's value
// threshold = 200;                  // would make the lambda above a compile error

// Instance fields are accessed through the captured 'this', so they CAN change underneath:
class Filterer { int limit = 100; Predicate<Order> p = o -> o.total().intValue() > limit; } // reads limit at call time

// Work-around for mutation (usually a smell): a one-element array, AtomicInteger, or a holder object.
var count = new AtomicInteger();
orders.forEach(o -> count.incrementAndGet());

How Java implements lambdas: not as anonymous inner classes. javac compiles the body into a private static (or instance) method and emits an invokedynamic instruction. On first execution, the bootstrap method LambdaMetafactory spins up a hidden class implementing the functional interface. A non-capturing lambda becomes a single cached instance (no allocation per evaluation). A capturing lambda allocates a small object holding the captured values, which escape analysis often eliminates (chapter 41).

Method references

Method references are shorthand for lambdas that only call an existing method:

Kind Syntax Equivalent lambda
Static method Integer::parseInt s -> Integer.parseInt(s)
Instance method of a particular object System.out::println, this::validate x -> System.out.println(x)
Instance method of an arbitrary object of a type String::toUpperCase, Order::total s -> s.toUpperCase() (the first parameter becomes the receiver)
Constructor ArrayList::new, Order[]::new () -> new ArrayList<>()

Subtlety: obj::method evaluates obj once, when the reference is created, so null::foo throws immediately. The lambda x -> obj.method(x) re-reads obj each call.

Composition

Functions combine into new functions. Java offers default methods for this:

Java
Function<String, String> trim = String::strip;
Function<String, String> lower = s -> s.toLowerCase(Locale.ROOT);
Function<String, String> normalise = trim.andThen(lower);       // lower(trim(x))
Function<String, String> same = lower.compose(trim);            // also lower(trim(x))

Predicate<Order> paid = Order::paid;
Predicate<Order> big = o -> o.total().compareTo(new BigDecimal("1000")) > 0;
Predicate<Order> flagged = paid.and(big).or(Order::manualReview).negate();
Predicate<String> notBlank = Predicate.not(String::isBlank);    // JDK 11

Comparator<Order> cmp = Comparator.comparing(Order::customer).thenComparing(Order::total);

Currying turns a function of several arguments into a chain of one-argument functions: add(a, b) becomes add(a)(b). Partial application fixes some arguments to produce a function of the rest. Haskell functions are curried by default (add 1 is a function). In Java, you can model it with Function<A, Function<B, C>>, but it's rarely idiomatic. Capturing lambdas (b -> add(1, b)) or small factory methods do the same job more readably.

Haskell
add :: Int -> Int -> Int        -- really Int -> (Int -> Int)
add a b = a + b
inc = add 1                     -- partial application
map (add 10) [1, 2, 3]          -- [11,12,13]

Streams

What a stream is

A java.util.stream.Stream<T> is not a collection. It's a lazily evaluated pipeline over a source (a collection, array, generator, I/O lines, or a range) that runs once:

Interactive diagram: Streams are lazy: one element at a time, and only as far as needed. It needs JavaScript; the text around it says the same.
  • Source: list.stream(), Arrays.stream(arr), Stream.of(…), IntStream.range(0, n), Files.lines(path), Stream.iterate(seed, hasNext, next), Stream.generate(supplier).
  • Intermediate operations (lazy, each returns a new stream): filter, map, flatMap, mapMulti, distinct, sorted, peek, limit, skip, takeWhile, dropWhile, and gather (Stream Gatherers, final in JDK 24).
  • Terminal operation (triggers execution and consumes the stream): forEach, collect, toList, reduce, count, min/max, anyMatch/allMatch/noneMatch, findFirst/findAny, toArray, iterator.

Nothing happens until the terminal operation. Then elements flow through the pipeline one at a time, vertically: each element passes through all stages before the next element starts. Batching per stage doesn't happen:

source 1..1M filter even map ×10 limit(2) toList() 1 → filter ✕ 2 → filter ✓ → map 20 → limit (1 of 2) → [20] 3 → filter ✕ 4 → filter ✓ → map 40 → limit (2 of 2) → [20, 40], short-circuit 5 … 1,000,000 are never pulled from the source the terminal op builds a Spliterator-driven chain of Sinks; elements are pushed through all stages one at a time; sorted() and distinct() are barriers that must buffer
Stream pipelines are lazy and element-at-a-time. Nothing runs until the terminal operation pulls; short-circuiting stops the source early.
Java
List<Integer> out = IntStream.rangeClosed(1, 1_000_000).boxed()
    .filter(x -> { System.out.println("filter " + x); return x % 2 == 0; })
    .map(x -> { System.out.println("map " + x); return x * 10; })
    .limit(2)
    .toList();
// prints: filter 1, filter 2, map 2, filter 3, filter 4, map 4: and stops

Stateless versus stateful intermediate operations: filter, map and flatMap handle each element independently. sorted and distinct are stateful: sorted must see all elements before emitting any, so it's a barrier that buffers everything. A sorted() on an infinite stream never finishes.

Short-circuiting operations (limit, findFirst, anyMatch, takeWhile) can finish without consuming the whole source. That's what makes infinite streams usable.

Single use: a stream can't be reused once a terminal operation runs (IllegalStateException: stream has already been operated upon or closed). Keep a Supplier<Stream<T>> if you need it twice, or better, collect to a list.

Resource streams (Files.lines, Files.list, JDBC-backed streams such as Spring Data's Stream<T> query methods) must be closed: try (var lines = Files.lines(p)) { … }.

Laziness in other languages

Language Lazy pipelines Eager collection ops
Java Stream (single-use) Collection methods: removeIf, replaceAll, forEach
Kotlin Sequence (asSequence()) List.map/filter (eager: each builds a new list)
C# LINQ over IEnumerable<T> (deferred execution: the query re-runs each time you enumerate it) .ToList(), .ToArray() materialise
Rust Iterator adapters (zero-cost; compile to loops) collect() materialises
C++20 std::views Algorithms on containers
Python Generators, itertools, generator expressions List comprehensions
Scala LazyList, view, Iterator Collections are eager
Haskell Everything is lazy (call-by-need) seq, bang patterns and strict data force evaluation
Elixir Stream Enum (eager)
Go Iterator functions iter.Seq (1.23), consumed by range Loops

Haskell's pervasive laziness allows elegant definitions over infinite structures (take 5 primes), but it makes performance and memory hard to predict: unevaluated thunks build up, causing "space leaks". Most languages choose strict by default, lazy on request.

Rust
// Rust iterators: lazy, zero-cost, and they drive the same pull model as Java streams
let first_two: Vec<u64> = (1..=1_000_000u64)
    .filter(|x| x % 2 == 0)
    .map(|x| x * 10)
    .take(2)
    .collect();
// Compiles to a loop with no intermediate allocation; LLVM often vectorises such chains.
// Calling .filter(...) without consuming it produces a compiler warning: "iterators are lazy and do nothing unless consumed".
C#
// C# deferred execution gotcha: the query runs at each enumeration
var expensive = orders.Where(o => Validate(o));     // nothing runs yet
var n = expensive.Count();                           // runs Validate for every order
var first = expensive.First();                       // runs again from the start
var list = expensive.ToList();                       // materialise once if you'll reuse it

flatMap and mapMulti

flatMap maps each element to a stream and flattens the results, which is how you handle one-to-many relationships:

Java
List<OrderLine> allLines = orders.stream()
    .flatMap(o -> o.lines().stream())
    .toList();

// mapMulti (JDK 16): push zero or more results without creating intermediate streams
List<String> skus = orders.stream()
    .<String>mapMulti((o, sink) -> { for (var l : o.lines()) if (l.qty() > 0) sink.accept(l.sku()); })
    .toList();

Collectors

collect(Collector) performs a mutable reduction: it accumulates into a container. Collectors provides the building blocks, and they compose:

Java
// To collections
List<Order> list = stream.toList();                              // JDK 16, unmodifiable
Set<String> customers = orders.stream().map(Order::customer).collect(Collectors.toSet());

// To maps: beware duplicates (IllegalStateException) and null values (NPE)
Map<OrderId, Order> byId = orders.stream()
    .collect(Collectors.toMap(Order::id, Function.identity()));
Map<String, BigDecimal> totalByCustomer = orders.stream()
    .collect(Collectors.toMap(Order::customer, Order::total, BigDecimal::add));   // merge function for duplicates

// Grouping: the SQL GROUP BY of streams, with downstream collectors
Map<String, List<Order>> byCustomer = orders.stream().collect(Collectors.groupingBy(Order::customer));
Map<String, Long> countByCustomer = orders.stream()
    .collect(Collectors.groupingBy(Order::customer, Collectors.counting()));
Map<Status, BigDecimal> revenueByStatus = orders.stream()
    .collect(Collectors.groupingBy(Order::status, () -> new EnumMap<>(Status.class),
             Collectors.reducing(BigDecimal.ZERO, Order::total, BigDecimal::add)));
Map<String, Optional<Order>> biggestPerCustomer = orders.stream()
    .collect(Collectors.groupingBy(Order::customer, Collectors.maxBy(Comparator.comparing(Order::total))));

// Partitioning: two groups by a predicate
Map<Boolean, List<Order>> paidSplit = orders.stream().collect(Collectors.partitioningBy(Order::paid));

// Strings and statistics
String csv = names.stream().collect(Collectors.joining(", ", "[", "]"));
IntSummaryStatistics stats = orders.stream().collect(Collectors.summarizingInt(Order::items));

// teeing (JDK 12): two collectors, combine their results
record MinMax(Optional<Order> min, Optional<Order> max) {}
var mm = orders.stream().collect(Collectors.teeing(
    Collectors.minBy(Comparator.comparing(Order::total)),
    Collectors.maxBy(Comparator.comparing(Order::total)),
    MinMax::new));

A Collector<T, A, R> is four functions: supplier (new container A), accumulator (add T to A), combiner (merge two As, needed for parallel streams) and finisher (A → R), plus characteristics (CONCURRENT, UNORDERED, IDENTITY_FINISH). Writing one is rarely needed. Collector.of(...) builds one from lambdas.

Gatherers (JDK 24, JEP 485) are to intermediate operations what collectors are to terminal ones: custom stateful stages such as windows, scans and deduplication by key.

Java
List<List<Integer>> windows = Stream.of(1,2,3,4,5).gather(Gatherers.windowSliding(3)).toList(); // [[1,2,3],[2,3,4],[3,4,5]]
List<Integer> running = Stream.of(1,2,3,4).gather(Gatherers.scan(() -> 0, Integer::sum)).toList(); // [1,3,6,10]

The equivalents elsewhere: Rust collect::<HashMap<_,_>>() plus the itertools crate (group_by/chunk_by, tuple_windows), C# GroupBy/ToDictionary/ToLookup, Kotlin groupBy/associateBy/partition/windowed, Python itertools.groupby (groups consecutive runs only, so sort first) and collections.Counter.

Optional and other "maybe" types

Optional<T> (Java 8) is a container that holds a value or is empty. It's meant as a return type that forces callers to consider absence:

Java
Optional<Customer> findByEmail(String email);

String city = repo.findByEmail(email)
    .map(Customer::address)           // stays empty if absent
    .map(Address::city)
    .filter(c -> !c.isBlank())
    .orElse("unknown");               // orElseGet(supplier) for expensive defaults; orElseThrow() otherwise

repo.findByEmail(email).ifPresentOrElse(this::greet, this::invite);
Optional<Discount> best = coupon.flatMap(this::lookupDiscount);   // flatMap when the function itself returns Optional

Guidelines (from the JDK designers):

  • Use it for return values that may be absent. Don't use it for fields, parameters, or collection elements, and don't put it in collections. Return an empty collection rather than an Optional<List>.
  • Never call get() without checking. Prefer orElseThrow() (same behaviour, honest name), map, orElse and ifPresent.
  • Optional itself must never be null.
  • It isn't serialisable, and it's an object, so it costs an allocation (often removed by escape analysis). There are primitive variants: OptionalInt, OptionalLong and OptionalDouble.
  • orElse(compute()) evaluates compute() always. Use orElseGet(this::compute).

Other languages build absence into the type system more deeply:

// Option<T> is an enum; there is no null. The compiler forces handling.
fn find_by_email(email: &str) -> Option<Customer> { None }

let city = find_by_email(email)
    .and_then(|c| c.address)                 // and_then = flatMap
    .map(|a| a.city)
    .filter(|c| !c.is_empty())
    .unwrap_or_else(|| "unknown".to_string());

// The ? operator also works on Option inside functions returning Option:
fn city_of(email: &str) -> Option<String> { Some(find_by_email(email)?.address?.city) }
// Option<&T> and Option<Box<T>> are the same size as a pointer (null-pointer optimisation).

Monads in plain words

You've now seen the same pattern four times: Optional.flatMap, Stream.flatMap, CompletableFuture.thenCompose, Rust's and_then and ?, and Haskell's do. In each, you have a value in a context (maybe-absent, many values, a value arriving later, a value-or-error) and a function that returns a new value in the same context, and you want to chain them without manually unpacking the context each time.

That's all a monad is: a type M<T> with

  • a way to wrap a plain value: Optional.of(x), Stream.of(x), CompletableFuture.completedFuture(x), Ok(x), pure x;
  • a way to chain: flatMap/thenCompose/and_then/>>=, which runs the next step only if and how the context allows (skip on empty, fan out over many, wait for completion, short-circuit on error);
  • laws (associativity and identity) guaranteeing that chaining behaves predictably however you group it.

A functor is the weaker version with only map. Haskell abstracts over all monads at once with higher-kinded types (chapter 36), so do-notation works for every one of them. Java, Rust and Kotlin give each type its own flatMap, plus special syntax for the important ones: Rust's ? for Result/Option and .await for futures, and C#'s async/await and LINQ query syntax (which is monadic comprehension).

Knowing the pattern helps in backend code: Mono/Flux in Reactor (chapter 48), CompletableFuture composition (chapter 38) and Result-style error handling are all the same chaining idea.

Side effects, parallelism and performance

Side effects in pipelines

Stream operations should be non-interfering (don't modify the source) and stateless (don't depend on mutable state that changes during execution). Side effects in map or filter are a code smell, and in parallel streams they're a bug:

Java
// BAD: mutating external state from a lambda
List<String> names = new ArrayList<>();
orders.stream().map(Order::customer).forEach(names::add);           // works sequentially, races in parallel
List<String> good = orders.stream().map(Order::customer).toList();  // GOOD

// BAD: modifying the source during the pipeline → ConcurrentModificationException or undefined results
orders.stream().filter(Order::cancelled).forEach(orders::remove);
orders.removeIf(Order::cancelled);                                  // GOOD

// peek is for debugging. It may not run at all: since JDK 9, count() can skip the pipeline when size is known
long n = List.of(1, 2, 3).stream().peek(System.out::println).count();  // prints nothing

forEach on a parallel stream runs in no particular order. Use forEachOrdered if order matters (it costs parallelism).

Parallel streams

.parallel() or collection.parallelStream() splits the source with a Spliterator and processes chunks on the common ForkJoinPool (with parallelism = cores − 1, plus the calling thread). It's sometimes faster. Often it isn't, and sometimes it's dangerous:

When it helps:

  • Large N with CPU-bound work per element (the NQ model: N × Q, the per-element cost, should exceed roughly 10,000).
  • Splittable sources: arrays, ArrayList and IntStream.range split perfectly. LinkedList, Stream.iterate and I/O-backed streams (Files.lines, before JDK 9's improvements) split poorly.
  • Cheap merging: sum and count combine cheaply. groupingBy into maps merges expensively (use groupingByConcurrent if order doesn't matter).
  • No ordering constraints: findAny over findFirst, unordered().

When it hurts:

  • Blocking I/O inside the pipeline (HTTP calls, JDBC). It occupies the shared common pool, starving every other parallel stream and CompletableFuture.supplyAsync() default task in the JVM. In a server, that's a latency disaster. Use virtual threads or a dedicated executor for I/O fan-out instead (chapter 38).
  • Small collections: splitting and coordination overhead dominate.
  • Stateful or ordered operations: sorted, limit on ordered streams, distinct.
  • Shared mutable state in lambdas: races.
  • Server workloads: requests already run in parallel across threads, so parallel streams compete with them for the same cores.
Java
// Measure, don't guess (JMH, chapter 41). A rule of thumb for request-handling code: don't use parallel streams.
long primes = LongStream.rangeClosed(2, 50_000_000).parallel().filter(Primes::isPrime).count(); // a good fit: CPU-bound, splittable

Other ecosystems: Rust's Rayon (par_iter()) gives work-stealing parallel iterators with data-race freedom guaranteed by the type system (closures must be Send + Sync). C# has PLINQ (AsParallel()), C++17 has parallel algorithms (std::execution::par), Go uses goroutines and errgroup explicitly, and Haskell has parMap with strategies.

Stream performance pitfalls

  1. Boxing: Stream<Integer> boxes every element. Use IntStream, LongStream and DoubleStream (mapToInt, sum(), boxed() only when needed).
  2. Hot loops: a stream pipeline has setup cost (object creation for the stages, lambda dispatch). In tight inner loops over small arrays, a plain for loop is often faster, though the JIT inlines a lot. Measure with JMH.
  3. sorted() / distinct() on huge streams buffer everything in memory.
  4. Repeated streaming: list.stream().filter(...).findFirst() inside a loop is O(n²). Build a Map once.
  5. collect(toList()) followed by .stream() again: unnecessary materialisation.
  6. Stream.iterate / generate without a limit: infinite.
  7. Exceptions in lambdas: checked exceptions need wrapping, and stack traces through stream internals are long and noisy.
  8. Readability: a 15-step pipeline with nested collectors can be harder to read and debug than a loop. Prefer streams when they make intent clearer.

Rust's iterators are the counter-example to "functional is slower": thanks to monomorphisation and inlining, iterator chains compile to the same machine code as hand-written loops, sometimes better because bounds checks are eliminated. Java's JIT achieves some of this, but boxing and megamorphic lambda call sites (one shared map implementation invoked with many different lambdas) limit it.

Recursion and tail calls

FP languages loop by recursion. A tail call is a call that's the very last action of a function. Languages with tail-call optimisation (TCO) reuse the stack frame, so tail recursion runs in constant stack space:

Language Tail calls
Scheme Guaranteed by the spec
Haskell, OCaml, F#, Erlang/Elixir Optimised (Erlang processes loop forever via tail recursion)
Scala Self-recursive tail calls optimised; @tailrec makes the compiler verify it
Kotlin tailrec modifier for self-recursion
Java None: deep recursion throws StackOverflowError (the default stack is ~512 KB–1 MB per platform thread)
C, C++, Rust, Zig Not guaranteed, though optimisers often do it. Zig has @call(.always_tail, f, args), and Rust has reserved the become keyword for guaranteed tail calls (in development)
Go, Python, JavaScript (most engines) No
Java
// Java: convert deep recursion to iteration (or an explicit stack) for unbounded inputs
static long sum(List<Integer> xs) { long s = 0; for (int x : xs) s += x; return s; }
// Recursive descent over trees is fine when depth is bounded (balanced trees: O(log n)).
Elixir
# Elixir: an accumulator makes recursion tail-recursive
def sum(list), do: sum(list, 0)
defp sum([], acc), do: acc
defp sum([h | t], acc), do: sum(t, acc + h)     # last call: no stack growth

Functional style in a Spring service

Putting it together: pure domain logic, side effects at the edges.

Java
@Service
public class PricingService {
    private final PriceRepository prices;     // edge: I/O
    private final Clock clock;                // edge: time, injected so the core stays testable

    public Quote quote(Cart cart) {
        var today = LocalDate.now(clock);
        var priceList = prices.findActive(today);          // imperative shell: fetch
        return Pricing.quote(cart, priceList, today);       // functional core: pure, unit-testable with no mocks
    }
}

final class Pricing {
    static Quote quote(Cart cart, PriceList list, LocalDate day) {
        var lines = cart.items().stream()
            .map(i -> new QuoteLine(i.sku(), i.qty(), list.unitPrice(i.sku(), day).multiply(BigDecimal.valueOf(i.qty()))))
            .toList();
        var subtotal = lines.stream().map(QuoteLine::amount).reduce(BigDecimal.ZERO, BigDecimal::add);
        var discount = Discounts.best(cart, subtotal, day);  // pure
        return new Quote(lines, subtotal, discount, subtotal.subtract(discount));
    }
}

Lab: streams under load

Run on JDK 21 on a 2-core machine (java -Xmx2g Lab.java); timings are from the last of five rounds. Five experiments on the stream behaviours that cause real bugs and slowdowns.

Experiment 1: side effects in a parallel stream

Java
List<Integer> shared = new ArrayList<>();
IntStream.range(0, 1_000_000).parallel().forEach(shared::add);         // a side effect on shared state
List<Integer> collected = IntStream.range(0, 1_000_000).parallel().boxed().toList();
Text
1,000,000 elements: parallel forEach into ArrayList kept 728,726 | parallel toList kept 1,000,000

.parallel() splits the work across the common fork-join pool's threads, which all called ArrayList.add at once and lost over a quarter of the elements (on other runs it can also throw ArrayIndexOutOfBoundsException during a resize). The collector version is correct because each thread fills its own container and the results are combined at the end: that's the reason collectors exist. Adding parallel() to a pipeline is only safe when every function in it is pure (or touches only thread-safe state), and forEach is ordered only with forEachOrdered.

Experiment 2: boxing, and an overflow nobody saw

Doubling and summing 5 million numbers:

Java
boxed.stream().map(x -> x * 2).reduce(0, Integer::sum);       // Stream<Integer>
Arrays.stream(prim).map(x -> x * 2).asLongStream().sum();     // IntStream, summed as long
for (int x : prim) c += x * 2L;                               // plain loop
Text
Stream<Integer> 595.6 ms | IntStream 6.8 ms | for loop 10.7 ms
reduce(0, Integer::sum) overflowed to -1009630016, true sum 24999995000000

Two lessons in one line. First, Stream<Integer> allocated a new Integer object for almost every intermediate value, and the boxing plus garbage collection made it about 90× slower than IntStream (the time varied from about 500 to 1,100 ms between runs, depending on GC; on a larger heap with more cores the gap shrinks but stays large). The primitive stream was as fast as the hand-written loop: streams are not inherently slow, boxing is. Use mapToInt, IntStream, LongStream and DoubleStream for numbers. Second, the boxed version silently overflowed: reduce(0, Integer::sum) keeps an int, and the true total of 25 trillion doesn't fit. Chapter 33's overflow lesson applies inside streams too.

Experiment 3: when parallel pays

Text
2 cores | 1,000 cheap items: sequential 0.073 ms, parallel 0.117 ms
        | 2M items × 200 sqrt each: sequential 2662 ms, parallel 1302 ms (2.0× faster)

Splitting work, handing it to other threads and merging results has a fixed cost, so a parallel stream over a small or cheap workload is slower. With enough CPU work per element it scales with the cores (here a perfect 2× on 2 cores). The rough rule from the JDK team is that the number of elements times the cost per element should be at least about 10,000 simple operations, and the source should split well (arrays, ArrayList, ranges split evenly; LinkedList, Stream.iterate and I/O sources don't). On a server, parallel streams also share one pool with every other request, so a CPU-heavy parallel stream in a request handler competes with everything else: measure before using them in backend code, and prefer explicit executors (chapter 38) for request-level parallelism.

Experiment 4: laziness and short-circuiting

Java
Stream.iterate(1, x -> x + 1).peek(count).filter(x -> x % 7 == 0).limit(3).toList();
IntStream.rangeClosed(1, 1000).boxed().peek(count).sorted().filter(…).limit(3).toList();
IntStream.rangeClosed(1, 1000).boxed().peek(count).sorted(Comparator.reverseOrder()).filter(…).limit(3).toList();
Text
first 3 multiples of 7 from an infinite stream touched 21 elements | 1..1000 with sorted(): 21 | with sorted(reverseOrder()): 1000

Elements flow through the pipeline one at a time, and limit(3) stops the source after the third match, so an infinite stream was safe: exactly 21 elements were generated. A stateful operation like sorted has to see every element before it can emit the first, which breaks short-circuiting (1,000 touched). The surprise in the middle: the range is already known to be sorted (the stream carries a SORTED flag), so the JDK skipped the natural-order sorted() entirely. This is one more reason not to rely on side effects in peek or map: the library is free to skip or reorder them.

Experiment 5: single use

Text
reusing a stream: stream has already been operated upon or closed

A stream is a one-shot iterator over its source, not a collection. Store the source (or a Supplier<Stream<T>>) and create a new stream for each traversal.

Try it yourself

  1. Replace experiment 1's ArrayList with Collections.synchronizedList and with ConcurrentLinkedQueue. Both are correct now; compare their speed with toList().
  2. Use Collectors.toMap on orders with duplicate customer names. What happens, and how does the three-argument form fix it?
  3. Write experiment 2 in Rust with iterators (iter().map().sum()) and in Haskell with sum (map (*2) xs). How do their speeds compare with IntStream, and why does Haskell's laziness need foldl'?
  4. Use JMH (org.openjdk.jmh) to repeat experiment 3 properly, with forks and warm-up, and find the crossover point on your machine.

Revision sheet: functional programming

Key ideas

  • First principles: functions as values, higher-order functions, pure functions, immutability, referential transparency, composition; effects pushed to the edges ("functional core, imperative shell").
  • Java: lambdas implement functional interfaces (Function, Predicate, Supplier, Consumer, UnaryOperator, BiFunction, primitive specialisations); method references (static, bound, unbound, constructor); captured variables must be effectively final.
  • Streams: source → lazy intermediate operations → terminal operation; stateless (map, filter) vs stateful (sorted, distinct); short-circuiting (findFirst, anyMatch, limit); flatMap, takeWhile, mapMulti, Stream.toList() (JDK 16), gatherers (Stream.gather, final in JDK 24) for custom intermediate operations.
  • Collectors: toList, toMap (with merge function), groupingBy (with downstream collectors), partitioningBy, joining, teeing.
  • Optional: a return type for absence; map/flatMap/orElse/orElseGet/orElseThrow.
  • Parallel streams: fork-join common pool; require pure functions and splittable sources; pay off only for large CPU-bound work.
  • Elsewhere: Haskell (purity, laziness, type classes, monads for effects), Scala and Kotlin collections, Clojure's persistent data and transducers, Rust iterators (zero-cost), F#/OCaml pipelines, JavaScript array methods (eager).

Numbers to remember

  • Lab: parallel forEach into an ArrayList lost about 27% of 1M elements; Stream<Integer> about 90× slower than IntStream; parallel was slower for 1,000 cheap items and 2.0× faster on 2 cores for heavy work.

Pitfalls

  • Side effects in map/filter/peek; mutating shared state from parallel streams.
  • Boxed streams for numeric work; reduce into int overflowing.
  • parallel() in request handlers on a shared pool; parallel over LinkedList or iterate.
  • Optional.get() without checking; Optional fields and parameters; orElse(expensiveCall()) instead of orElseGet.
  • toMap throwing on duplicate keys; stream pipelines so long they're harder to read than a loop.

Glossary

  • Higher-order function: one that takes or returns functions.
  • Referential transparency: an expression can be replaced by its value without changing behaviour.
  • Lazy evaluation: computing only when, and as much as, needed.
  • Short-circuiting: stopping early once the result is known.
  • Collector: a mutable reduction (supplier, accumulator, combiner, finisher).
  • Gatherer: a user-defined intermediate stream operation (JDK 24).