forked from javaevolved/javaevolved.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptional-or.json
More file actions
50 lines (50 loc) · 1.67 KB
/
Copy pathoptional-or.json
File metadata and controls
50 lines (50 loc) · 1.67 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
50
{
"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();\nif (!cfg.isPresent()) {\n cfg = secondary();\n}\nif (!cfg.isPresent()) {\n cfg = defaults();\n}",
"modernCode": "Optional<Config> cfg = primary()\n .or(this::secondary)\n .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)"
}
]
}