Commit 409fe8d
committed
feat(Package2): add Test class showing Optional map from String to Integer
What
- Added Test class in package Package2.
- Demonstrates use of Optional.map to transform a String into its length (Integer).
- main method:
- Calls getName(2) which returns Optional<String> containing "ram".
- Applies map to compute string length.
- Prints result only if present using ifPresent.
- getName(int id) returns Optional.of("ram") for any id.
Why
- Shows how Optional.map can change the contained type safely (String → Integer).
- Demonstrates functional programming style for value transformation without null checks.
- Provides clear teaching example of how Optional supports type-safe transformations.
How
- Defined getName(int id) to return Optional<String>.
- In main, invoked getName and stored in Optional<String> optional.
- Applied map(x -> x.length()) to produce Optional<Integer>.
- Printed integer result via optional1.ifPresent(System.out::println).
Logic
- Inputs: integer id (example uses 2).
- Outputs: 3 printed to stdout (length of "ram").
- Flow:
1. Call getName(2) → returns Optional.of("ram").
2. Apply map(x -> x.length()) → Optional.of(3).
3. Call ifPresent → prints 3.
- Edge cases handled:
- If getName returned Optional.empty(), map propagates emptiness and nothing prints.
- No NullPointerException risk; safety ensured by Optional.
- Complexity / performance: O(1) operations, negligible cost.
- Concurrency / thread-safety:
- Optional and string are immutable.
- Safe for multi-threaded usage.
- Error handling:
- No exceptions thrown.
- Safe handling of absent values through Optional API.
Real-life applications
- Safely deriving numeric properties (length, size, hash) from optional data.
- Template for chaining type transformations in functional pipelines.
- Useful in parsing or data validation flows where input may be missing.
- Teaching aid for understanding Optional’s map and type conversion features.
Notes
- getName currently always returns non-empty Optional; real implementations should return Optional.empty() for missing or invalid ids.
- Method reference String::length can replace lambda for brevity.
- This pattern scales with chained maps for more complex transformations.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 69e4398 commit 409fe8d
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