Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b6gdUKYmBw6bUKcM7t
optional
Companion code for the ankurm.com post "Java Optional: Best Practices, Anti-Patterns and orElse vs
orElseGet" (https://ankurm.com/java-optional-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) | or, stream, ifPresentOrElse are Java 9; no-argument orElseThrow() is Java 10; isEmpty() is Java 11 (see output/00-since.txt, read from the JDK's own src.zip). |
| JSpecify | 1.0.0 | Annotations only. No nullness checker is run in this module. |
| JUnit Jupiter | 5.11.0 |
Quickstart
export JAVA_HOME=/path/to/jdk-25
mvn compile
java -cp "target/classes:$(mvn -q dependency:build-classpath -Dmdep.outputFile=/dev/stdout)" \
com.ankurm.optional.OrElseVsOrElseGetDemo
scripts/run-all.sh regenerates every file in output/ and runs the tests.
What's in here
| File | Output | What it shows |
|---|---|---|
CreationDemo |
01-creation.txt |
empty, of, ofNullable, and what of(null) does |
ExtractionDemo |
02-extraction.txt |
get, orElse, orElseGet, orElseThrow, ifPresent, ifPresentOrElse |
TransformDemo |
03-transform.txt |
map, flatMap, filter, or |
RepositoryDemo |
04-repository.txt |
The lookup pattern and three ways to react to a miss |
OrElseVsOrElseGetDemo |
05-orelsevsorelseget.txt |
Eager versus lazy defaults, and a default that throws |
AntiPatternsDemo |
06-antipatterns.txt |
Each misuse, run for real |
StreamInteropDemo |
07-streaminterop.txt |
Optional.stream(), primitive Optionals, lazy or() chains |
NullableContrastDemo |
08-nullablecontrast.txt |
Optional versus JSpecify @Nullable |
OptionalContractTest |
09-contract-test.txt |
Asserts every behavioural claim in the post |
| (script) | 00-since.txt, 00-javap-optionalint.txt |
Which Java release added each method; the method list of OptionalInt (no map, filter or or) |
Timing figures in 05 are indicative; everything else is deterministic.