Commit a2ed984
committed
feat(OperatorInterfaceDemo): add demo using UnaryOperator and BinaryOperator with apply()
What
- Added OperatorInterfaceDemo class demonstrating usage of java.util.function.UnaryOperator and BinaryOperator.
- Defined:
- UnaryOperator<Integer> a → multiplies input by 2.
- BinaryOperator<Integer> b → adds two integers.
- Executed both with apply():
- a.apply(5) → 10.
- b.apply(5, 5) → 10.
- Printed results with descriptive messages.
Why
- Shows how to execute lambda expressions stored in operator interfaces.
- Clarifies difference between printing operator reference vs executing with apply().
- Educational example highlighting the purpose of UnaryOperator and BinaryOperator as specializations of Function and BiFunction.
How
- Declared lambdas for arithmetic operations.
- Invoked apply() method on both operator instances.
- Printed results to stdout.
Logic
- Inputs: integer 5 for unary; integers 5 and 5 for binary.
- Outputs:
- "Unary result (2 * 5): 10".
- "Binary result (5 + 5): 10".
- Flow:
1. a.apply(5) → 2 * 5 → 10.
2. b.apply(5, 5) → 5 + 5 → 10.
3. Print results.
- Edge cases: trivial arithmetic; no exceptions expected.
- Complexity / performance: O(1).
- Concurrency / thread-safety: lambdas are stateless, safe across threads.
- Error handling: not applicable.
Real-life applications
- UnaryOperator: transformations like scaling numbers, normalizing data, incrementing values.
- BinaryOperator: aggregation (sum, min, max), often used with Stream.reduce().
- Useful in mathematical pipelines, configuration merging, or data combination scenarios.
Notes
- Demonstrates execution with apply(); without it, only the object reference prints.
- Cleaner than earlier version since no unused methods present.
- Method references (Integer::sum, x -> x * 2 as inline) can further simplify usage in production code.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent b021236 commit a2ed984
File tree
1 file changed
+6
-4
lines changed- Java 8 Crash Course/Unary operators and Binary operators/src
1 file changed
+6
-4
lines changedLines changed: 6 additions & 4 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
12 | 12 | | |
13 | 13 | | |
14 | 14 | | |
15 | | - | |
| 15 | + | |
16 | 16 | | |
17 | 17 | | |
18 | 18 | | |
19 | 19 | | |
20 | 20 | | |
21 | 21 | | |
22 | 22 | | |
23 | | - | |
| 23 | + | |
| 24 | + | |
24 | 25 | | |
25 | | - | |
| 26 | + | |
| 27 | + | |
26 | 28 | | |
27 | 29 | | |
28 | 30 | | |
29 | 31 | | |
30 | | - | |
| 32 | + | |
0 commit comments