Lambdas and the Stream API: functional interfaces, lazy pipelines, Collectors and the traps
When streams make code easier to read and when they make it harder: lazy pipelines that run one element at a time, why side effects and parallel lose data, toMap duplicate keys, Optional, the cost of boxing measured with a benchmark, Stream Gatherers (JDK 24) and how to review stream code an AI wrote. Code runs on JDK 21 and JDK 25.
On this page
1. The problem
AI turns a revenue for loop into a stream and adds .parallel() "to make it faster". Tests with 50 orders pass. In production with 100,000 orders the total is off by about 10% every run. A week later toMap throws because one customer has two orders.
2. Key idea
A for loop is a command: "do this step, then that one". A stream is a description of the result. Intermediate steps (filter, map) are lazy: only when a terminal operation (collect, findFirst) is called does data flow through, one element at a time. Lambda code that assumes an order or a moment of execution is wrong.
Assumption from for loops |
In a stream |
|---|---|
| Every line in the body runs | peek may not run (count() can skip the pipeline) |
| Runs on one thread | parallel() splits work onto ForkJoinPool.commonPool(), shared by the whole JVM |
| Throw anything | Function.apply declares no throws: checked exceptions must be wrapped |
| Duplicate keys overwrite | toMap throws on duplicates |
2.1 What to use when?
| Tool | Use when | Don't use when |
|---|---|---|
| Stream | filtering, transforming, grouping, counting | early exits on several conditions, stateful running totals |
for loop |
complex break, mutating several variables, checked exceptions |
it's just filter + map + toList |
parallel() |
millions of elements, CPU-heavy, batch jobs | inside request handlers, with I/O |
toMap |
keys are certainly unique, or you pass a merge function | keys are "usually" unique: use groupingBy |
Optional |
return type for "might be absent" | fields, parameters, DTOs |
The test: a reviewer understands it in seconds. Past 4–5 steps, extract a named method.
2.2 Are streams slow?
The big cost is boxing (Stream<Integer> holds objects), not streams. A rough run over 10 million numbers: IntStream ~30 ms, Stream<Long> + reduce ~73 ms. For large data use mapToLong, IntStream. A few hundred elements with I/O: don't bother.
3. In Java
record Order(String id, String customer, String status, long amount) {}
// PAID revenue per customer, ordered map
Map<String, Long> revenue = orders.stream()
.filter(o -> o.status().equals("PAID"))
.collect(groupingBy(Order::customer, TreeMap::new, summingLong(Order::amount)));
// {an=320, binh=300}
// Keys may repeat: always say how to merge
Map<String, Long> maxByCustomer = orders.stream()
.collect(toMap(Order::customer, Order::amount, Math::max));
// {an=200, binh=300, chi=50}
List<String> bigIds = orders.stream().filter(o -> o.amount() >= 100).map(Order::id).toList();
// [o1, o3, o5]; bigIds.add(...) throws UnsupportedOperationException
String name = findById(id).map(Order::customer).orElse("none"); // orElse always evaluates its argumentOther languages: C# LINQ and Kotlin Sequence are lazy too; Node.js has Object.groupBy. JDK 24+ has Stream Gatherers (Gatherers.windowFixed, scan, mapConcurrent) for custom intermediate operations.
Common traps: peek, reused streams, checked exceptions, orElse
- Reusing a stream throws
IllegalStateException. Return a collection; don't store aStreamin a field. peek:List.of(1, 2, 3).stream().peek(System.out::println).count()prints nothing. Don't put business logic inpeek.- Checked exceptions:
map(Files::readString)doesn't compile. Don'tcatchandreturn null; wrap inUncheckedIOExceptionkeeping the cause. orElse(x)always evaluatesx, even when a value is present; ifxis expensive (a DB query) useorElseGet(() -> x).- Order:
groupingByreturns aHashMapby default; passTreeMap::newwhen order matters. sortedon an infinite stream hangs; putlimitfirst.
4. Working with AI
Delegate to AI: turning simple for loops into filter/map/collect, generating test data with duplicate keys and nulls.
Check yourself:
- No lambda writes to an outside list, map or variable.
- Every
toMaphas a merge function, or a reason why keys are unique. - No
catchreturningnullin lambdas; no business logic inpeek. -
parallel()isn't in a request handler and doesn't wrap I/O. - If old code mutated the returned list, it wasn't switched to
toList().
5. Exercises
Exercise 1: Review a "same behaviour" refactor
AI wrote this, describing it as "same behaviour, faster thanks to parallel". Find the bug, name a test, fix it.
Map<String, Long> revenue = new HashMap<>();
orders.parallelStream()
.filter(o -> o.status().equals("PAID"))
.forEach(o -> revenue.merge(o.customer(), o.amount(), Long::sum));Solution to Exercise 1
The lambda writes to a HashMap from several commonPool threads; HashMap isn't thread-safe, so updates are lost. With 100,000 orders of 1 each, five runs gave 90038, 90914, 89912, 86979 and one ConcurrentModificationException.
Test: compare the total with a sequential for loop over 100,000 orders, repeated 10 times since the bug doesn't show every run.
Fix: orders.stream().filter(...).collect(groupingBy(Order::customer, summingLong(Order::amount))). groupingBy is correct even in parallel, but only turn on parallel() after measuring a gain.
Exercise 2: Read the incident
At 14:00, p99 of every API goes from 80 ms to 2.5 s, CPU at 20%. The /reprice endpoint is receiving a batch of 5,000 SKUs. Thread dump: 9 ForkJoinPool.commonPool-worker-* threads sit in SocketInputStream.read, going through skus.parallelStream().map(pricingClient::fetch). Diagnose, act within 15 minutes, fix the root cause.
Solution to Exercise 2
- Diagnosis:
commonPoolis shared by the whole JVM with only cores − 1 threads./repriceholds all 9 waiting on HTTP, so every otherparallelStreamqueues. CPU is low because threads are waiting on the network. - 15 minutes: block or rate-limit
/reprice, or deploy a build without.parallel(). - Root fix: I/O doesn't belong in
commonPool. Use a dedicated executor, or virtual threads with aSemaphore; JDK 24+ hasGatherers.mapConcurrent(16, pricingClient::fetch). Add HTTP client timeouts.
Summary
- Intermediate steps are lazy; nothing runs without a terminal operation.
- Stream lambdas are pure; results leave through
collect. toMapneeds a merge function when keys can repeat.parallel()uses the sharedcommonPool: not for I/O or request handlers.- With running state or checked exceptions, a
forloop reads better.
Further reading: Nested classes and lambdas.
Self-compiled notes from official documentation and hands-on practice.
Practice interview questions on this topic
- What is a functional interface? When do you use a lambda versus a method reference?
- How does a Stream work: intermediate vs terminal operations, laziness, and map vs flatMap?
- How do you use Optional properly? How does orElse differ from orElseGet?
- How do Collectors.groupingBy and partitioningBy work? What is a downstream collector?
- What happens when Collectors.toMap hits a duplicate key? How do reduce, collect and toList() differ?
- Are streams slower than for loops? When would you use parallel streams in a backend?
Comments
Community rules