Commit 69e4398
committed
feat(Package2): add Practice class demonstrating Optional map and ifPresent
What
- Added Practice class in package Package2.
- Demonstrates simple use of Optional with map and ifPresent.
- main method:
- Calls getName(2) which returns Optional<String> containing "ram".
- Transforms value to uppercase using map.
- Prints transformed value only if present.
- getName(int id) returns Optional.of("ram").
Why
- Shows minimal, focused example of using Optional in functional style.
- Reinforces idea of avoiding explicit null checks with map and ifPresent.
- Serves as a teaching/demo snippet for Optional usage in simple cases.
How
- Defined getName(int id) to return Optional<String>.
- In main, assigned result to Optional<String> optional.
- Applied map(x -> x.toUpperCase()) to transform string if present.
- Printed result with ifPresent(System.out::println).
Logic
- Inputs: integer id (example uses 2).
- Outputs: "RAM" printed to stdout.
- Flow:
1. Call getName(2) → returns Optional.of("ram").
2. Apply map to transform value to uppercase → Optional.of("RAM").
3. Call ifPresent → prints "RAM".
- Edge cases handled:
- If getName returned Optional.empty(), map would propagate emptiness and nothing would print.
- Avoids NullPointerException since value presence is managed by Optional.
- Complexity / performance: O(1) operations, very lightweight.
- Concurrency / thread-safety:
- Optional and strings are immutable.
- Safe for multi-threaded execution.
- Error handling:
- No checked exceptions.
- Safe null-avoidance built-in through Optional.
Real-life applications
- Template for transforming and consuming values that may or may not exist.
- Introductory example for teaching Optional API.
- Useful for wrapping method return values where nulls might otherwise appear.
- Demonstrates safe, functional-style handling in Java.
Notes
- Current getName always returns non-empty Optional; in real-world use, it should sometimes return Optional.empty() for missing data.
- Method reference String::toUpperCase could replace lambda for brevity.
- This pattern scales naturally to more complex transformations with chained maps.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent ecc52a4 commit 69e4398
File tree
1 file changed
+20
-0
lines changed- Java 8 Crash Course/Lambda Expression/Optional/src/Package2
1 file changed
+20
-0
lines changedLines changed: 20 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 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
0 commit comments