Commit b021236
committed
feat(Demo): add example using UnaryOperator and BinaryOperator
What
- Added Demo class to illustrate java.util.function.UnaryOperator and BinaryOperator.
- Defined:
- UnaryOperator<Integer> doubleValue → multiplies input by 2.
- BinaryOperator<Integer> addValues → adds two integers.
- Applied lambdas using apply() and printed results:
- doubleValue.apply(5) → 10.
- addValues.apply(3, 4) → 7.
Why
- Demonstrates specialized functional interfaces where input and output types are the same.
- Provides educational contrast:
- UnaryOperator for single-argument transformations.
- BinaryOperator for combining two arguments of the same type.
- Useful for arithmetic, aggregation, and transformations in functional pipelines.
How
- Declared UnaryOperator and BinaryOperator with lambda expressions.
- Executed them with sample inputs.
- Printed results to stdout.
Logic
- Inputs: integers 5 for unary, 3 and 4 for binary.
- Outputs:
- "Result of UnaryOperator (5 * 2): 10".
- "Result of BinaryOperator (3 + 4): 7".
- Flow:
1. doubleValue.apply(5) → 2 * 5 → 10.
2. addValues.apply(3, 4) → 3 + 4 → 7.
3. Print both 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 in this simple demo.
Real-life applications
- UnaryOperator:
- Increment, negate, or normalize values.
- Common in map() operations on streams.
- BinaryOperator:
- Combining values, such as reductions (sum, max).
- Frequently used with Stream.reduce(BinaryOperator).
- Ideal for functional-style data transformations and aggregations.
Notes
- UnaryOperator and BinaryOperator are specializations of Function and BiFunction.
- Use them when argument and return types match to improve clarity.
- Method references (e.g., Integer::sum) can replace simple lambdas for readability.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 6adda80 commit b021236
File tree
1 file changed
+3
-3
lines changed- Java 8 Crash Course/Unary operators and Binary operators/src
1 file changed
+3
-3
lines changedLines changed: 3 additions & 3 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
12 | 12 | | |
13 | 13 | | |
14 | 14 | | |
15 | | - | |
16 | | - | |
| 15 | + | |
| 16 | + | |
17 | 17 | | |
18 | 18 | | |
19 | 19 | | |
20 | 20 | | |
21 | | - | |
| 21 | + | |
0 commit comments