optional: java.util.Optional module (factories, extraction, orElse vs orElseGet, anti-patterns, Stream interop, JSpecify contrast)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b6gdUKYmBw6bUKcM7t
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
cca173d104
commit
47e4ccbefa
@@ -0,0 +1,41 @@
|
||||
# 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
|
||||
|
||||
```bash
|
||||
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.
|
||||
@@ -0,0 +1,19 @@
|
||||
Compiled from "OptionalInt.java"
|
||||
public final class java.util.OptionalInt {
|
||||
public static java.util.OptionalInt empty();
|
||||
public static java.util.OptionalInt of(int);
|
||||
public int getAsInt();
|
||||
public boolean isPresent();
|
||||
public boolean isEmpty();
|
||||
public void ifPresent(java.util.function.IntConsumer);
|
||||
public void ifPresentOrElse(java.util.function.IntConsumer, java.lang.Runnable);
|
||||
public java.util.stream.IntStream stream();
|
||||
public int orElse(int);
|
||||
public int orElseGet(java.util.function.IntSupplier);
|
||||
public int orElseThrow();
|
||||
public <X extends java.lang.Throwable> int orElseThrow(java.util.function.Supplier<? extends X>) throws X;
|
||||
public boolean equals(java.lang.Object);
|
||||
public int hashCode();
|
||||
public java.lang.String toString();
|
||||
static {};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
isEmpty() since 11
|
||||
ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) since 9
|
||||
or(Supplier<? extends Optional<? extends T>> supplier) since 9
|
||||
stream() since 9
|
||||
orElseThrow() since 10
|
||||
orElseThrow(Supplier<? extends X> exceptionSupplier) since 1.8 (class-level)
|
||||
@@ -0,0 +1,6 @@
|
||||
empty : Optional.empty
|
||||
of : Optional[ankur]
|
||||
ofNullable : Optional.empty
|
||||
of(null) : java.lang.NullPointerException, message=null
|
||||
equals : true
|
||||
empty==empty : true
|
||||
@@ -0,0 +1,10 @@
|
||||
isPresent : true
|
||||
isEmpty : true
|
||||
get (present): Mumbai
|
||||
get (empty) : java.util.NoSuchElementException: No value present
|
||||
orElseThrow(): java.util.NoSuchElementException: No value present
|
||||
orElse : Unknown City
|
||||
orElseGet : DefaultCity
|
||||
orElseThrow(s): java.lang.IllegalStateException: City must be set
|
||||
ifPresent : City is Mumbai
|
||||
ifPresentOrElse: No city configured
|
||||
@@ -0,0 +1,10 @@
|
||||
name : Ankur
|
||||
pincode : 411001
|
||||
missing pin : N/A
|
||||
map to null : Optional.empty
|
||||
map nests : Optional[Optional[Address[city=Pune, pincode=411001]]]
|
||||
flatMap flat : Optional[Address[city=Pune, pincode=411001]]
|
||||
flatMap city : Pune
|
||||
filter match : 411001
|
||||
filter miss : not 400xx
|
||||
or fallback : 110001
|
||||
@@ -0,0 +1,5 @@
|
||||
Found : Laptop
|
||||
Required : Laptop
|
||||
Phone - Rs 29999.00
|
||||
Product not available
|
||||
Missing : Product 99 not found
|
||||
@@ -0,0 +1,7 @@
|
||||
orElse on PRESENT : default built 1 time(s)
|
||||
orElseGet on PRESENT : default built 0 time(s)
|
||||
orElse on EMPTY : default built 1 time(s)
|
||||
orElseGet on EMPTY : default built 1 time(s)
|
||||
orElse on PRESENT with failing default : threw default lookup failed
|
||||
orElseGet on PRESENT with failing default : cached
|
||||
200 calls, slow default (indicative): orElse >= 1000 ms: true, orElseGet < 100 ms: true
|
||||
@@ -0,0 +1,11 @@
|
||||
1 isPresent+get : ANKUR | map+orElse : ANKUR
|
||||
2 Optional field : java.io.NotSerializableException: java.util.Optional
|
||||
2 nullable field : serialized OK, getEmail() = Optional[[email protected]]
|
||||
3 greet(empty) : Hello, guest
|
||||
3 greet(null) : NullPointerException, Cannot invoke "java.util.Optional.orElse(Object)" because "name" is null
|
||||
4 return null : NullPointerException, Cannot invoke "java.util.Optional.map(java.util.function.Function)" because the return value of "com.ankurm.optional.AntiPatternsDemo.brokenLookup()" is null
|
||||
4 return empty() : 0
|
||||
5 of(map.get(..)) : NullPointerException (use ofNullable)
|
||||
5 ofNullable : Optional.empty
|
||||
6 Optional<List> : empty list wrapped = Optional[[]] | plain list = []
|
||||
6 states : Optional<List> has 3 (empty, present-empty, present-full), List has 2
|
||||
@@ -0,0 +1,16 @@
|
||||
filter+get : [a, c]
|
||||
flatMap(::stream) : [a, c]
|
||||
stream sizes : present=1 empty=0
|
||||
findFirst hit : Optional[8]
|
||||
findFirst miss : Optional.empty
|
||||
max : Optional[pune]
|
||||
OptionalInt : OptionalInt[9] getAsInt=9
|
||||
OptionalDouble : OptionalDouble.empty orElse(-1)=-1.0
|
||||
or() chain, cache hits:
|
||||
consulted cache
|
||||
result = Optional[from-cache]
|
||||
or() chain, cache and db miss:
|
||||
consulted cache
|
||||
consulted database
|
||||
consulted config
|
||||
result = Optional[from-config]
|
||||
@@ -0,0 +1,6 @@
|
||||
display (null nickname) : acc-1
|
||||
display (set nickname) : Ankur
|
||||
rawNickname : null
|
||||
describe(null) : no value
|
||||
@Nullable targets : [TYPE_USE]
|
||||
package is @NullMarked : true
|
||||
@@ -0,0 +1,4 @@
|
||||
-------------------------------------------------------------------------------
|
||||
Test set: com.ankurm.optional.OptionalContractTest
|
||||
-------------------------------------------------------------------------------
|
||||
Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.135 s -- in com.ankurm.optional.OptionalContractTest
|
||||
@@ -0,0 +1,48 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ankurm</groupId>
|
||||
<artifactId>java-core-examples</artifactId>
|
||||
<version>1.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>optional</artifactId>
|
||||
<name>optional</name>
|
||||
<description>java.util.Optional end to end: factories, extraction, map/flatMap/filter/or, the orElse vs orElseGet evaluation trap, anti-patterns that fail for real, Stream interop and the JSpecify contrast.</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jspecify</groupId>
|
||||
<artifactId>jspecify</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.11.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<release>25</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.2.5</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
NOISE='JAVA_TOOL_OPTIONS|_JAVA_OPTIONS|Djavax\.net\.ssl|^WARNING'
|
||||
|
||||
# Which Java release introduced each Optional method, read from the JDK's own source.
|
||||
python3 - "$(dirname "$(dirname "$(readlink -f "$(command -v javac)")")")/lib/src.zip" > output/00-since.txt <<'PY'
|
||||
import re, sys, zipfile
|
||||
src = zipfile.ZipFile(sys.argv[1]).read('java.base/java/util/Optional.java').decode()
|
||||
for sig in ['isEmpty', 'ifPresentOrElse', 'or', 'stream', 'orElseThrow']:
|
||||
for m in re.finditer(r'/\*\*((?:(?!\*/).)*?)\*/\s*public [^\n]*?\b' + sig + r'\(([^)]*)\)', src, re.S):
|
||||
since = re.search(r'@since\s+(\S+)', m.group(1))
|
||||
print(f"{sig}({' '.join(m.group(2).split())})".ljust(70), 'since', since.group(1) if since else '1.8 (class-level)')
|
||||
PY
|
||||
|
||||
javap java.util.OptionalInt 2>&1 | grep -vE "$NOISE" > output/00-javap-optionalint.txt
|
||||
|
||||
mvn -q -B compile
|
||||
i=1
|
||||
for d in CreationDemo ExtractionDemo TransformDemo RepositoryDemo OrElseVsOrElseGetDemo AntiPatternsDemo StreamInteropDemo NullableContrastDemo; do
|
||||
f=$(printf 'output/%02d-%s.txt' "$i" "$(echo "$d" | sed 's/Demo$//' | tr 'A-Z' 'a-z')")
|
||||
java -cp "target/classes:$(mvn -q -B dependency:build-classpath -Dmdep.outputFile=/dev/stdout 2>/dev/null | tail -1)" "com.ankurm.optional.$d" 2>&1 | grep -vE "$NOISE" > "$f"
|
||||
i=$((i+1))
|
||||
done
|
||||
|
||||
mvn -q -B test
|
||||
cp target/surefire-reports/com.ankurm.optional.OptionalContractTest.txt output/09-contract-test.txt
|
||||
echo "Regenerated output/00-09."
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.ankurm.optional;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Each misuse is run for real, so the failure you read about is the failure you can reproduce. */
|
||||
public class AntiPatternsDemo {
|
||||
|
||||
// 1. Optional as a field of a Serializable class.
|
||||
static class BadCustomer implements Serializable {
|
||||
String name = "Ankur";
|
||||
Optional<String> email = Optional.of("[email protected]");
|
||||
}
|
||||
|
||||
// The alternative: store the plain (possibly null) value, expose an Optional.
|
||||
static class GoodCustomer implements Serializable {
|
||||
String name = "Ankur";
|
||||
private String email = "[email protected]"; // may be null
|
||||
|
||||
Optional<String> getEmail() {
|
||||
return Optional.ofNullable(email);
|
||||
}
|
||||
}
|
||||
|
||||
static void serialize(Object o) throws IOException {
|
||||
try (ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())) {
|
||||
out.writeObject(o);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Optional as a parameter: the caller can still pass null.
|
||||
static String greet(Optional<String> name) {
|
||||
return "Hello, " + name.orElse("guest");
|
||||
}
|
||||
|
||||
// 3. A method that returns Optional but hands back null.
|
||||
static Optional<String> brokenLookup() {
|
||||
return null;
|
||||
}
|
||||
|
||||
static Optional<String> correctLookup() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
// 4. Optional wrapping a collection.
|
||||
static Optional<List<String>> ordersOptional() {
|
||||
return Optional.of(List.of());
|
||||
}
|
||||
|
||||
static List<String> ordersList() {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// isPresent + get versus a single expression
|
||||
Optional<String> nick = Optional.of("ankur");
|
||||
String viaGet = nick.isPresent() ? nick.get().toUpperCase() : "GUEST";
|
||||
String viaMap = nick.map(String::toUpperCase).orElse("GUEST");
|
||||
System.out.println("1 isPresent+get : " + viaGet + " | map+orElse : " + viaMap);
|
||||
|
||||
// Optional field
|
||||
try {
|
||||
serialize(new BadCustomer());
|
||||
} catch (IOException e) {
|
||||
System.out.println("2 Optional field : " + e.getClass().getName() + ": " + e.getMessage());
|
||||
}
|
||||
serialize(new GoodCustomer());
|
||||
System.out.println("2 nullable field : serialized OK, getEmail() = " + new GoodCustomer().getEmail());
|
||||
|
||||
// Optional parameter
|
||||
System.out.println("3 greet(empty) : " + greet(Optional.empty()));
|
||||
try {
|
||||
greet(null);
|
||||
} catch (NullPointerException e) {
|
||||
System.out.println("3 greet(null) : NullPointerException, " + e.getMessage());
|
||||
}
|
||||
|
||||
// Returning null from an Optional method
|
||||
try {
|
||||
brokenLookup().map(String::length).orElse(0);
|
||||
} catch (NullPointerException e) {
|
||||
System.out.println("4 return null : NullPointerException, " + e.getMessage());
|
||||
}
|
||||
System.out.println("4 return empty() : " + correctLookup().map(String::length).orElse(0));
|
||||
|
||||
// Optional.of on a value that can be null
|
||||
Map<String, String> config = new HashMap<>();
|
||||
try {
|
||||
Optional.of(config.get("timeout"));
|
||||
} catch (NullPointerException e) {
|
||||
System.out.println("5 of(map.get(..)) : NullPointerException (use ofNullable)");
|
||||
}
|
||||
System.out.println("5 ofNullable : " + Optional.ofNullable(config.get("timeout")));
|
||||
|
||||
// Collections
|
||||
System.out.println("6 Optional<List> : empty list wrapped = " + ordersOptional()
|
||||
+ " | plain list = " + ordersList());
|
||||
System.out.println("6 states : Optional<List> has 3 (empty, present-empty, present-full), List has 2");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.ankurm.optional;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/** The three factory methods, and what each does with null. */
|
||||
public class CreationDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 1. empty(): a known absence.
|
||||
Optional<String> emptyUsername = Optional.empty();
|
||||
System.out.println("empty : " + emptyUsername);
|
||||
|
||||
// 2. of(value): the value must not be null. null is a programming error here.
|
||||
Optional<String> presentUsername = Optional.of("ankur");
|
||||
System.out.println("of : " + presentUsername);
|
||||
|
||||
// 3. ofNullable(value): for values you do not control (DB rows, HTTP, System properties).
|
||||
String rawValue = System.getProperty("user.nickname"); // null unless -Duser.nickname is set
|
||||
Optional<String> safeUsername = Optional.ofNullable(rawValue);
|
||||
System.out.println("ofNullable : " + safeUsername);
|
||||
|
||||
// of(null) fails immediately, at the call site that made the mistake.
|
||||
try {
|
||||
Optional.of(rawValue);
|
||||
} catch (NullPointerException e) {
|
||||
System.out.println("of(null) : " + e.getClass().getName() + ", message=" + e.getMessage());
|
||||
}
|
||||
|
||||
// Optional values compare by content.
|
||||
System.out.println("equals : " + Optional.of("a").equals(Optional.of("a")));
|
||||
System.out.println("empty==empty : " + (Optional.empty() == Optional.empty()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.ankurm.optional;
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Every way to get a value out, from unsafe to safe. */
|
||||
public class ExtractionDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Optional<String> city = Optional.of("Mumbai");
|
||||
Optional<String> noCity = Optional.empty();
|
||||
|
||||
System.out.println("isPresent : " + city.isPresent());
|
||||
System.out.println("isEmpty : " + noCity.isEmpty()); // Java 11+
|
||||
|
||||
// get(): works when present, throws when empty.
|
||||
System.out.println("get (present): " + city.get());
|
||||
try {
|
||||
noCity.get();
|
||||
} catch (NoSuchElementException e) {
|
||||
System.out.println("get (empty) : " + e.getClass().getName() + ": " + e.getMessage());
|
||||
}
|
||||
|
||||
// The no-argument orElseThrow() (Java 10+) is the same behaviour with an honest name.
|
||||
try {
|
||||
noCity.orElseThrow();
|
||||
} catch (NoSuchElementException e) {
|
||||
System.out.println("orElseThrow(): " + e.getClass().getName() + ": " + e.getMessage());
|
||||
}
|
||||
|
||||
// Defaults and domain exceptions.
|
||||
System.out.println("orElse : " + noCity.orElse("Unknown City"));
|
||||
System.out.println("orElseGet : " + noCity.orElseGet(ExtractionDemo::fetchDefaultCity));
|
||||
try {
|
||||
noCity.orElseThrow(() -> new IllegalStateException("City must be set"));
|
||||
} catch (IllegalStateException e) {
|
||||
System.out.println("orElseThrow(s): " + e.getClass().getName() + ": " + e.getMessage());
|
||||
}
|
||||
|
||||
// Side effects.
|
||||
city.ifPresent(c -> System.out.println("ifPresent : City is " + c));
|
||||
noCity.ifPresentOrElse(
|
||||
c -> System.out.println("ifPresentOrElse: City found " + c),
|
||||
() -> System.out.println("ifPresentOrElse: No city configured"));
|
||||
}
|
||||
|
||||
private static String fetchDefaultCity() {
|
||||
return "DefaultCity";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.ankurm.optional;
|
||||
|
||||
import java.lang.annotation.Target;
|
||||
import java.util.Optional;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Optional and JSpecify answer different questions. Optional is a runtime value for a method result.
|
||||
* JSpecify is a compile-time contract on any type, and it is only enforced when a checker runs.
|
||||
*/
|
||||
public class NullableContrastDemo {
|
||||
|
||||
static class Account {
|
||||
private final String id;
|
||||
private final @Nullable String nickname; // a field: use the annotation, not Optional
|
||||
|
||||
Account(String id, @Nullable String nickname) {
|
||||
this.id = id;
|
||||
this.nickname = nickname;
|
||||
}
|
||||
|
||||
// A return value that may be absent: Optional is the better signal for a caller.
|
||||
Optional<String> nickname() {
|
||||
return Optional.ofNullable(nickname);
|
||||
}
|
||||
|
||||
// The same fact expressed as an annotation instead.
|
||||
@Nullable String rawNickname() {
|
||||
return nickname;
|
||||
}
|
||||
|
||||
String display() {
|
||||
return nickname().orElse(id);
|
||||
}
|
||||
}
|
||||
|
||||
static String describe(@Nullable String s) {
|
||||
return s == null ? "no value" : s.toUpperCase();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Account a = new Account("acc-1", null);
|
||||
Account b = new Account("acc-2", "Ankur");
|
||||
System.out.println("display (null nickname) : " + a.display());
|
||||
System.out.println("display (set nickname) : " + b.display());
|
||||
System.out.println("rawNickname : " + a.rawNickname());
|
||||
System.out.println("describe(null) : " + describe(null));
|
||||
|
||||
Target t = Nullable.class.getAnnotation(Target.class);
|
||||
System.out.println("@Nullable targets : " + java.util.Arrays.toString(t.value()));
|
||||
System.out.println("package is @NullMarked : "
|
||||
+ (NullableContrastDemo.class.getPackage().getAnnotation(org.jspecify.annotations.NullMarked.class) != null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.ankurm.optional;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/** orElse(x) builds x before the call; orElseGet(supplier) builds it only when needed. */
|
||||
public class OrElseVsOrElseGetDemo {
|
||||
|
||||
static int built = 0;
|
||||
|
||||
static String expensiveDefault() {
|
||||
built++;
|
||||
return "default";
|
||||
}
|
||||
|
||||
static String failingDefault() {
|
||||
throw new IllegalStateException("default lookup failed");
|
||||
}
|
||||
|
||||
static String slowDefault() {
|
||||
try {
|
||||
Thread.sleep(5);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return "default";
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Optional<String> present = Optional.of("cached");
|
||||
Optional<String> empty = Optional.empty();
|
||||
|
||||
built = 0;
|
||||
present.orElse(expensiveDefault());
|
||||
System.out.println("orElse on PRESENT : default built " + built + " time(s)");
|
||||
|
||||
built = 0;
|
||||
present.orElseGet(OrElseVsOrElseGetDemo::expensiveDefault);
|
||||
System.out.println("orElseGet on PRESENT : default built " + built + " time(s)");
|
||||
|
||||
built = 0;
|
||||
empty.orElse(expensiveDefault());
|
||||
System.out.println("orElse on EMPTY : default built " + built + " time(s)");
|
||||
|
||||
built = 0;
|
||||
empty.orElseGet(OrElseVsOrElseGetDemo::expensiveDefault);
|
||||
System.out.println("orElseGet on EMPTY : default built " + built + " time(s)");
|
||||
|
||||
// The sharper trap: a default that throws breaks orElse even when a value is present.
|
||||
try {
|
||||
present.orElse(failingDefault());
|
||||
} catch (IllegalStateException e) {
|
||||
System.out.println("orElse on PRESENT with failing default : threw " + e.getMessage());
|
||||
}
|
||||
System.out.println("orElseGet on PRESENT with failing default : " + present.orElseGet(OrElseVsOrElseGetDemo::failingDefault));
|
||||
|
||||
// Cost, indicative only: 200 calls, default takes at least 5 ms to build.
|
||||
long t0 = System.nanoTime();
|
||||
for (int i = 0; i < 200; i++) present.orElse(slowDefault());
|
||||
long orElseMs = (System.nanoTime() - t0) / 1_000_000;
|
||||
|
||||
t0 = System.nanoTime();
|
||||
for (int i = 0; i < 200; i++) present.orElseGet(OrElseVsOrElseGetDemo::slowDefault);
|
||||
long orElseGetMs = (System.nanoTime() - t0) / 1_000_000;
|
||||
|
||||
System.out.println("200 calls, slow default (indicative): orElse >= 1000 ms: " + (orElseMs >= 1000)
|
||||
+ ", orElseGet < 100 ms: " + (orElseGetMs < 100));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.ankurm.optional;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/** The canonical use: a lookup that may not find anything. Three ways a caller can react. */
|
||||
public class RepositoryDemo {
|
||||
|
||||
record Product(int id, String name, double price) {}
|
||||
|
||||
static class ProductRepository {
|
||||
private final Map<Integer, Product> store = new HashMap<>();
|
||||
|
||||
ProductRepository() {
|
||||
store.put(1, new Product(1, "Laptop", 79999.0));
|
||||
store.put(2, new Product(2, "Phone", 29999.0));
|
||||
}
|
||||
|
||||
Optional<Product> findById(int productId) {
|
||||
return Optional.ofNullable(store.get(productId));
|
||||
}
|
||||
}
|
||||
|
||||
static class ProductService {
|
||||
private final ProductRepository repository = new ProductRepository();
|
||||
|
||||
// Pattern 1: hand the Optional to the caller; they decide what "missing" means.
|
||||
Optional<Product> getProduct(int productId) {
|
||||
return repository.findById(productId);
|
||||
}
|
||||
|
||||
// Pattern 2: absence is an error.
|
||||
Product requireProduct(int productId) {
|
||||
return repository.findById(productId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Product " + productId + " not found"));
|
||||
}
|
||||
|
||||
// Pattern 3: transform, then default.
|
||||
String getFormattedPrice(int productId) {
|
||||
return repository.findById(productId)
|
||||
.map(p -> String.format("%s - Rs %.2f", p.name(), p.price()))
|
||||
.orElse("Product not available");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ProductService service = new ProductService();
|
||||
|
||||
service.getProduct(1).ifPresent(p -> System.out.println("Found : " + p.name()));
|
||||
System.out.println("Required : " + service.requireProduct(1).name());
|
||||
System.out.println(service.getFormattedPrice(2));
|
||||
System.out.println(service.getFormattedPrice(99));
|
||||
try {
|
||||
service.requireProduct(99);
|
||||
} catch (IllegalArgumentException e) {
|
||||
System.out.println("Missing : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.ankurm.optional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/** Optional.stream(), Optional-returning terminal operations, primitive Optionals and lazy or(). */
|
||||
public class StreamInteropDemo {
|
||||
|
||||
static Optional<String> lookup(String source, String result) {
|
||||
System.out.println(" consulted " + source);
|
||||
return Optional.ofNullable(result);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Optional<String>> raw = List.of(Optional.of("a"), Optional.empty(), Optional.of("c"), Optional.empty());
|
||||
|
||||
// Two ways to keep only the present values.
|
||||
List<String> old = raw.stream().filter(Optional::isPresent).map(Optional::get).toList();
|
||||
List<String> modern = raw.stream().flatMap(Optional::stream).toList();
|
||||
System.out.println("filter+get : " + old);
|
||||
System.out.println("flatMap(::stream) : " + modern);
|
||||
System.out.println("stream sizes : present=" + Optional.of("x").stream().count()
|
||||
+ " empty=" + Optional.empty().stream().count());
|
||||
|
||||
// Terminal operations that return Optional.
|
||||
System.out.println("findFirst hit : " + Stream.of(3, 8, 12).filter(n -> n > 5).findFirst());
|
||||
System.out.println("findFirst miss : " + Stream.of(3, 8, 12).filter(n -> n > 50).findFirst());
|
||||
System.out.println("max : " + Stream.of("pune", "mumbai", "nashik").max(String::compareTo));
|
||||
|
||||
// Primitive specialisations: no boxing, different method names.
|
||||
OptionalInt maxInt = IntStream.of(3, 9, 4).max();
|
||||
OptionalDouble avg = IntStream.empty().average();
|
||||
System.out.println("OptionalInt : " + maxInt + " getAsInt=" + maxInt.getAsInt());
|
||||
System.out.println("OptionalDouble : " + avg + " orElse(-1)=" + avg.orElse(-1));
|
||||
|
||||
// or(): a lazy chain of fallbacks. Later sources are not consulted once one answers.
|
||||
System.out.println("or() chain, cache hits:");
|
||||
Optional<String> hit = lookup("cache", "from-cache")
|
||||
.or(() -> lookup("database", "from-db"))
|
||||
.or(() -> lookup("config", "from-config"));
|
||||
System.out.println(" result = " + hit);
|
||||
|
||||
System.out.println("or() chain, cache and db miss:");
|
||||
Optional<String> miss = lookup("cache", null)
|
||||
.or(() -> lookup("database", null))
|
||||
.or(() -> lookup("config", "from-config"));
|
||||
System.out.println(" result = " + miss);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.ankurm.optional;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/** map, flatMap, filter and or on a small domain model. */
|
||||
public class TransformDemo {
|
||||
|
||||
record Address(String city, String pincode) {}
|
||||
record User(String name, Address address) {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Optional<User> userWithAddress = Optional.of(new User("Ankur", new Address("Pune", "411001")));
|
||||
Optional<User> userWithoutAddress = Optional.of(new User("Alex", null));
|
||||
|
||||
// map: transform the value; an empty Optional stays empty and the function is never called.
|
||||
Optional<String> userName = userWithAddress.map(User::name);
|
||||
System.out.println("name : " + userName.orElse("N/A"));
|
||||
|
||||
Optional<String> pincode = userWithAddress.map(User::address).map(Address::pincode);
|
||||
System.out.println("pincode : " + pincode.orElse("N/A"));
|
||||
|
||||
// A function that returns null turns into an empty Optional, not an NPE.
|
||||
Optional<String> missingPin = userWithoutAddress.map(User::address).map(Address::pincode);
|
||||
System.out.println("missing pin : " + missingPin.orElse("N/A"));
|
||||
System.out.println("map to null : " + Optional.of("x").map(s -> (String) null));
|
||||
|
||||
// map vs flatMap when the function itself returns an Optional.
|
||||
Optional<Optional<Address>> nested = userWithAddress.map(u -> Optional.ofNullable(u.address()));
|
||||
Optional<Address> flat = userWithAddress.flatMap(u -> Optional.ofNullable(u.address()));
|
||||
System.out.println("map nests : " + nested);
|
||||
System.out.println("flatMap flat : " + flat);
|
||||
System.out.println("flatMap city : " + flat.map(Address::city).orElse("N/A"));
|
||||
|
||||
// filter: keep the value only if the predicate holds.
|
||||
System.out.println("filter match : " + pincode.filter(p -> p.startsWith("411")).orElse("not 411xx"));
|
||||
System.out.println("filter miss : " + pincode.filter(p -> p.startsWith("400")).orElse("not 400xx"));
|
||||
|
||||
// or (Java 9+): fall back to another Optional, evaluated lazily.
|
||||
System.out.println("or fallback : " + missingPin.or(() -> Optional.of("110001")).orElse("?"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
@NullMarked
|
||||
package com.ankurm.optional;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.ankurm.optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.NotSerializableException;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Pins every behavioural claim the article makes. */
|
||||
class OptionalContractTest {
|
||||
|
||||
@Test
|
||||
void ofNullThrowsButOfNullableDoesNot() {
|
||||
assertThrows(NullPointerException.class, () -> Optional.of(null));
|
||||
assertEquals(Optional.empty(), Optional.ofNullable(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getOnEmptyThrowsNoSuchElement() {
|
||||
NoSuchElementException e = assertThrows(NoSuchElementException.class, () -> Optional.empty().get());
|
||||
assertEquals("No value present", e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void orElseIsEagerAndOrElseGetIsLazy() {
|
||||
Optional<String> present = Optional.of("v");
|
||||
AtomicInteger eager = new AtomicInteger();
|
||||
AtomicInteger lazy = new AtomicInteger();
|
||||
|
||||
present.orElse(build(eager));
|
||||
present.orElseGet(() -> build(lazy));
|
||||
|
||||
assertEquals(1, eager.get());
|
||||
assertEquals(0, lazy.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void orElseWithFailingDefaultThrowsEvenWhenPresent() {
|
||||
Optional<String> present = Optional.of("v");
|
||||
assertThrows(IllegalStateException.class, () -> present.orElse(fail()));
|
||||
assertEquals("v", present.orElseGet(OptionalContractTest::fail));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapReturningNullBecomesEmpty() {
|
||||
assertEquals(Optional.empty(), Optional.of("x").map(s -> (String) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapNestsAndFlatMapFlattens() {
|
||||
Optional<Optional<String>> nested = Optional.of("x").map(Optional::of);
|
||||
Optional<String> flat = Optional.of("x").flatMap(Optional::of);
|
||||
assertEquals(Optional.of(Optional.of("x")), nested);
|
||||
assertEquals(Optional.of("x"), flat);
|
||||
}
|
||||
|
||||
@Test
|
||||
void orIsLazy() {
|
||||
AtomicInteger consulted = new AtomicInteger();
|
||||
Optional<String> r = Optional.of("a").or(() -> {
|
||||
consulted.incrementAndGet();
|
||||
return Optional.of("b");
|
||||
});
|
||||
assertEquals("a", r.orElseThrow());
|
||||
assertEquals(0, consulted.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void flatMapStreamDropsEmpties() {
|
||||
List<Optional<String>> raw = List.of(Optional.of("a"), Optional.empty(), Optional.of("c"));
|
||||
assertEquals(List.of("a", "c"), raw.stream().flatMap(Optional::stream).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void optionalIsNotSerializable() {
|
||||
NotSerializableException e = assertThrows(NotSerializableException.class, () -> {
|
||||
try (ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())) {
|
||||
out.writeObject(new Holder());
|
||||
}
|
||||
});
|
||||
assertEquals("java.util.Optional", e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returningNullFromAnOptionalMethodBlowsUpTheCaller() {
|
||||
assertThrows(NullPointerException.class, () -> AntiPatternsDemo.brokenLookup().isPresent());
|
||||
}
|
||||
|
||||
static class Holder implements java.io.Serializable {
|
||||
Optional<String> value = Optional.of("x");
|
||||
}
|
||||
|
||||
private static String build(AtomicInteger counter) {
|
||||
counter.incrementAndGet();
|
||||
return "default";
|
||||
}
|
||||
|
||||
private static String fail() {
|
||||
throw new IllegalStateException("boom");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user