Commit 023b5a1
committed
feat: implement lambda expressions with functional interface
WHAT was done:
- Defined a `@FunctionalInterface` named `MyLambda` with a single abstract method `display()`.
- Replaced the traditional class-based implementation and anonymous inner class with a lambda expression.
- Demonstrated how a lambda expression provides a concise syntax for implementing functional interfaces.
KEY LEARNINGS:
1. Functional Interfaces:
- An interface with exactly one abstract method.
- Marked with `@FunctionalInterface` for compiler validation.
- Example: `MyLambda` with `display()`.
2. Lambda Expression:
- Syntax: `() -> { /* body */ }`
- Provides a clean, inline implementation of the functional interface method.
- Eliminates boilerplate code compared to:
a) Concrete class (`My1 implements MyLambda`)
b) Anonymous inner class.
3. Execution Flow:
- `MyLambda m = () -> { System.out.println("Hello world"); };`
- Invoking `m.display()` runs the lambda body, printing "Hello world".
BENEFITS:
- More concise and readable compared to anonymous classes.
- Encourages functional programming style in Java.
- Works seamlessly with Java APIs expecting functional interfaces (Streams, Executors, etc.).
REAL-LIFE APPLICATIONS:
- ✅ Event handling in GUIs (e.g., button click listeners).
- ✅ Passing behavior into methods (strategy pattern replacement).
- ✅ Parallel and stream processing (`map`, `filter`, `forEach`).
- ✅ Replacing boilerplate anonymous classes in multithreading (e.g., `Runnable`).
RULE OF THUMB:
- Use lambda expressions whenever implementing functional interfaces.
- Reserve full class/anonymous classes only when multiple methods or complex logic are needed.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent d82de2d commit 023b5a1
1 file changed
+5
-9
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | | - | |
| 2 | + | |
3 | 3 | | |
4 | 4 | | |
5 | 5 | | |
| |||
27 | 27 | | |
28 | 28 | | |
29 | 29 | | |
30 | | - | |
31 | | - | |
32 | | - | |
33 | | - | |
34 | | - | |
35 | | - | |
36 | | - | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
37 | 33 | | |
38 | | - | |
| 34 | + | |
0 commit comments