-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathoptional-or.yaml
More file actions
49 lines (49 loc) · 1.43 KB
/
optional-or.yaml
File metadata and controls
49 lines (49 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
---
id: 45
slug: "optional-or"
title: "Optional.or() fallback"
category: "streams"
difficulty: "intermediate"
jdkVersion: "9"
oldLabel: "Java 8"
modernLabel: "Java 9+"
oldApproach: "Nested Fallback"
modernApproach: ".or() chain"
oldCode: |-
Optional<Config> cfg = primary();
if (!cfg.isPresent()) {
cfg = secondary();
}
if (!cfg.isPresent()) {
cfg = defaults();
}
modernCode: |-
Optional<Config> cfg = primary()
.or(this::secondary)
.or(this::defaults);
summary: "Chain Optional fallbacks without nested checks."
explanation: "Optional.or() returns the original Optional if it has a value, otherwise\
\ evaluates the supplier to get an alternative Optional. Suppliers are lazy — only\
\ called when needed."
whyModernWins:
- icon: "🔗"
title: "Chainable"
desc: "Stack fallbacks in a readable pipeline."
- icon: "⚡"
title: "Lazy evaluation"
desc: "Fallback suppliers only execute if needed."
- icon: "📖"
title: "Declarative"
desc: "Reads as 'try primary, or secondary, or defaults'."
support:
state: "available"
description: "Widely available since JDK 9 (Sept 2017)"
prev: "streams/optional-ifpresentorelse"
next: "streams/predicate-not"
related:
- "streams/stream-iterate-predicate"
- "streams/stream-gatherers"
- "streams/stream-of-nullable"
docs:
- title: "Optional.or()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Optional.html#or(java.util.function.Supplier)"