Commit 7b2a438
committed
feat(OptionalDemo): add demo using map, filter, and orElse with Optional
What
- Added OptionalDemo class demonstrating core Optional operations.
- Creates an Optional containing "hello".
- Applies the following transformations:
- map(String::toUpperCase) → "HELLO".
- filter(s -> s.startsWith("H")) → value passes filter and remains.
- orElse("world") → fallback used only if empty; here value remains "HELLO".
- Prints final result to stdout.
Why
- Showcases how Optional can be used in a fluent, functional style.
- Demonstrates chaining of map, filter, and orElse to safely transform and consume values.
- Provides educational example for developers learning Optional API idioms.
How
- Constructed Optional<String> using Optional.of("hello").
- Applied map to convert string to uppercase.
- Applied filter to retain value only if condition matches.
- Used orElse to provide fallback in case of empty Optional.
- Printed final result.
Logic
- Inputs: none (hardcoded value "hello").
- Outputs: "HELLO" printed to stdout.
- Flow:
1. Start with Optional.of("hello").
2. map(String::toUpperCase) → Optional.of("HELLO").
3. filter(s -> s.startsWith("H")) → condition true, remains Optional.of("HELLO").
4. orElse("world") → since value present, returns "HELLO".
5. Print result.
- Edge cases handled:
- If initial value did not start with "H", filter would make Optional empty, and orElse would return "world".
- No null risks due to Optional.
- Complexity / performance: O(1) per operation, negligible cost.
- Concurrency / thread-safety:
- Optional and string values are immutable.
- Safe across threads.
- Error handling:
- No exceptions expected.
- orElse guarantees fallback for empty cases.
Real-life applications
- Data sanitization and conditional validation pipelines.
- Applying transformations with safe defaults.
- Avoiding verbose null-checks in business logic.
- Useful for input validation (e.g., checking prefixes, applying case normalization).
Notes
- This example demonstrates fluent chaining in Optional.
- orElse eagerly evaluates argument; for expensive defaults, use orElseGet.
- Method references improve readability (e.g., String::toUpperCase).
- Optional should primarily be used for return values, not fields or serialization.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 409fe8d commit 7b2a438
File tree
1 file changed
+17
-0
lines changed- Java 8 Crash Course/Lambda Expression/Optional/src
1 file changed
+17
-0
lines changedLines changed: 17 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
0 commit comments