Commit 10a608c
committed
feat: demonstrate lambda expressions with parameters and return values
WHAT was done:
- Defined a functional interface `MyLambda2` with a method `add(int x, int y)` returning an int.
- Implemented the interface using a lambda expression `(a, b) -> a + b`.
- Executed the lambda in `main()` to add two numbers (20 + 30) and printed the result.
KEY LEARNINGS:
1. Functional Interface:
- `@FunctionalInterface` ensures only one abstract method.
- This single abstract method can be represented with a lambda.
2. Lambda with Parameters and Return Value:
- Syntax: `(parameters) -> expression`.
- Example: `(a, b) -> a + b`.
- If the body is a single expression, `return` and braces `{}` are optional.
3. Simplification:
- Traditional anonymous class implementation:
```
MyLambda2 m = new MyLambda2() {
public int add(int a, int b) {
return a + b;
}
};
```
- Equivalent lambda: `MyLambda2 m = (a, b) -> a + b;`.
4. Benefits:
- Less boilerplate, concise, readable.
- Directly focuses on *what* to compute, not *how* to declare.
REAL-LIFE APPLICATIONS:
- ✅ Arithmetic operations (sum, product, etc.) in functional pipelines.
- ✅ Passing custom behavior into APIs (e.g., comparators in sorting).
- ✅ Stream API usage (`map`, `reduce`, `filter`) where operations involve transformations.
- ✅ Replacing anonymous classes in concurrency (`Callable`, `Runnable`).
RULE OF THUMB:
- Use lambdas whenever a functional interface implementation is short and inline.
- Prefer concise form `(a, b) -> a + b` for simple logic.
- Use block form `{ return ...; }` when multiple statements are needed.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent bfeb9a0 commit 10a608c
1 file changed
+4
-10
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | 1 | | |
4 | | - | |
5 | | - | |
| 2 | + | |
6 | 3 | | |
7 | 4 | | |
8 | 5 | | |
9 | 6 | | |
10 | 7 | | |
11 | | - | |
12 | 8 | | |
13 | | - | |
14 | 9 | | |
15 | 10 | | |
16 | 11 | | |
17 | 12 | | |
18 | 13 | | |
19 | 14 | | |
20 | | - | |
21 | | - | |
| 15 | + | |
| 16 | + | |
22 | 17 | | |
23 | 18 | | |
24 | | - | |
25 | | - | |
| 19 | + | |
0 commit comments