Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b49nGy7tcEjVUa3WAA
streams
Companion code for the ankurm.com post "Java Stream API Tutorial with Examples + Collectors
Cookbook" (https://ankurm.com/java-streams-api-complete-guide/). Module in java-core-examples,
the Java-core series. There is deliberately no docs/ folder: the explanations live in the
post itself.
Versions this was built and tested against
| Component | Version | Notes |
|---|---|---|
| JDK | 25.0.5.1+2 (Temurin, LTS) | Stream.toList() is Java 16; takeWhile/dropWhile/iterate with predicate/ofNullable are Java 9; Collectors.filtering/flatMapping are Java 9; teeing is Java 12; mapMulti is Java 16; Stream Gatherers are final in JDK 24 (JEP 485). |
| JUnit Jupiter | 5.11.0 | |
| Maven | 3.9.11 |
Quickstart
export JAVA_HOME=/path/to/jdk-25
mvn compile
java -cp target/classes com.ankurm.streams.CollectorsCookbookDemo
scripts/run-all.sh regenerates every file in output/. scripts/run.sh <ClassName> runs one
demo ad hoc.
What's in here
| File | What it shows |
|---|---|
CreationDemo |
Every common way to obtain a stream. |
LazyPipelineDemo |
Nothing runs without a terminal operation; elements flow one at a time; short-circuiting; count() skipping peek; the single-use IllegalStateException. |
IntermediateOpsDemo |
filter, map, flatMap, mapMulti, sorted, distinct, limit, skip, takeWhile, dropWhile. |
TerminalOpsDemo |
reduce, the match family, findFirst, Stream.toList() versus Collectors.toList(). |
CollectorsCookbookDemo |
groupingBy + downstream collectors, partitioningBy, toMap traps, filtering, flatMapping, teeing. |
PrimitiveStreamsDemo |
IntStream statistics and the silent int overflow. |
ParallelDemo |
Associative versus non-associative reduce, shared mutable state, encounter order. |
GatherersDemo |
windowFixed, windowSliding, scan, fold, mapConcurrent and a custom Gatherer. |
LoopToStreamDemo |
Converting a for loop, and the behaviours that change. |
StreamsContractTest |
Pins the claims in the post as assertions (12/12). |
output/00-10 |
Captured runs; 00 is javap java.util.stream.Gatherers straight from the JDK. |
Non-deterministic output
ParallelDemo prints a number that depends on the machine and on thread scheduling: the
parallel result of the non-associative reduce, and the final size of the ArrayList that
parallel forEach wrote into without synchronisation. The committed output/07-parallel.txt is
one real run on a 2-vCPU sandbox (common pool parallelism 1); yours will differ.