Lambda Expression in Java
Lambda Expression:-
Don't worry about the name. It's the same old Java programming with a bit of a different flavor. So, A lambda expression is a concise way to express a method of a class in an expression.
It just reduces the words required to write a function or call a function or write an anonymous class. Lambda expressions in Java are instances of Functional Interface
What is Functional Interface
A functional interface is an interface that contains exactly one abstract method.
For Example:-
public interface FunctionalInterface { public void onlyMethod(); }
java.lang.Runnable Is the most frequently used Functional Interface
Why we use Lambda?
Enables functional programming and leads to Readable and precise code
Lambda Expression can do all this for us
- Can be returned from functions
- Can be passed to functions
- Can be assigned to a variable
- Can define anonymous functions
Sample lambda expression :-
() -> System.out.println("Hello World"); (a) -> System.out.println(a); (a, b) -> System.out.println(a + ", " + b);
The lambda expression came in java 8 and above, let me show you how we used to work before lambda expression.
Now create a file name as
eg.java
class MyClass implements Runnable { public void run() { System.out.println("Bhopal is City of lake"); } }
Now,
class Main { public static void main(String args[]) { Thread t=new Thread(new MyClass()); t.start(); } }
This can also be done using anonymous inner class, this feature was used in Java 7 and earlier.
Here is example using anonymous inner class:-
class Main { public static void main(String args[]) { Thread t=new Thread(new Runnable() { public void run() { System.out.println("Anonymous inner class"); } }); t.start(); } }
Now finally check it out in the lambda way :-
class Main { public static void main(String args[]) { Thread t=new Thread(()-> System.out.println("Anonymous inner class"); t.start(); } }
lambda operator can be:
Zero parameter:
() -> System.out.println("Zero parameter lambda");
One parameter:
(p) -> System.out.println("One parameter: " + p);
It is not mandatory to use parentheses, if the type of that variable can be inferred from the context
Multiple parameters:
(p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);
Please note: Lambda expressions are just like functions and they accept parameters just like functions.
If you still have problem in understanding check out this video Lambda Expression by Prakash Pandey https://www.youtube.com/watch?v=6rAfwW-dApk
Hope you find it helpful and feel free to add a comment and I’ll make sure to improve my self.
Thank You
Prakash Pandey
Good Explanation
ReplyDeleteNiceeeeee
ReplyDeleteWell explained!
ReplyDeleteMuch informative
ReplyDeletecan you make blog on multithreading .... good content
ReplyDeleteThat's a great way to explain!!!
ReplyDeleteNice work👏