Skip to content

Commit 10a608c

Browse files
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

File tree

1 file changed

+4
-10
lines changed

1 file changed

+4
-10
lines changed
Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,19 @@
1-
package lamdademo1;
2-
31
@FunctionalInterface
4-
interface MyLambda
5-
{
2+
interface MyLambda2 {
63
//public void display(String str);
74
public int add(int x,int y);
85
}
96

107
public class LamdaDemo {
11-
128
public static void main(String[] args) {
13-
149
/*MyLambda m=(s)->{System.out.println(s);};
1510
m.display("Hello World");*/
1611

1712
/*MyLambda m=(a,b)->{return a+b;};
1813
System.out.println(m.add(20,30));*/
1914

20-
MyLambda m=(a,b)->a+b;
21-
int r=m.add(20, 30);
15+
MyLambda2 m = (a,b) -> a + b;
16+
int r = m.add(20, 30);
2217
System.out.println(r);
2318
}
24-
25-
}
19+
}

0 commit comments

Comments
 (0)