Skip to content

Commit 023b5a1

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

File tree

1 file changed

+5
-9
lines changed

1 file changed

+5
-9
lines changed

Section22Lambda Expressions/src/LambdaDemo.java

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
@FunctionalInterface
2-
interface MyLambda{
2+
interface MyLambda {
33
public void display();
44
}
55

@@ -27,12 +27,8 @@ public void display() {
2727
};
2828
*/
2929

30-
//MyLambda Mehtod.Method it self is an object in lambda class.
31-
MyLambda m=
32-
() ->
33-
{
34-
System.out.println("Hello world");
35-
};
36-
m.display();
30+
//MyLambda Method. Method itself is an object in lambda class.
31+
MyLambda m= () -> {System.out.println("Hello world");};
32+
m.display();
3733
}
38-
}
34+
}

0 commit comments

Comments
 (0)