Check out more about Java 8 LTS in our other blog. We will learn about one of the Java 8 features i.e. Lambda Expressions.
What are Lambda Expressions?
Lambda expressions, also called closures are a new feature in Java 8. It is helpful in writing anonymous methods in a concise and flexible way. Lambda expressions are used to implement the functional interfaces.
How to write Lambda Expression?
Let us analyze it through a code snippet. We will look through lambda expression using the Thread example and Runnable interface which has only one method called – run().
Before Java 8, we used to write the below code –
public class LambdaExample {
public static void main(String[] args) {
MyThread mt1 = new MyThread();
Thread t1 = new Thread(mt1);
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Running from Thread T2..!!");
}
});
t2.start();
}
}
class MyThread implements Runnable {
@Override
public void run() {
System.out.println("Running from MyThread..!!");
}
}
Output:
Running from MyThread..!!
Running from Thread T2..!!
After Java 8, the same implementation using lambda expression –
public class LambdaExample {
public static void main(String[] args) {
Thread t3 = new Thread(() -> { System.out.println("Running from Thread T3..! lambda yay!");
});
t3.start();
}
}
Output:
Running from Thread T3..! lambda yay!
What have we achieved here?
If you observe carefully, we are able to shorten the anonymous method and write it in a more concise way. Please note that lambda expression only works with functional interfaces.
To understand more about this, watch out this video from Telusko –
Further readings
- https://javaconceptoftheday.com/java-8-lambda-expressions/
- A Stackoverflow Discussion
- https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Feel free to share your thoughts on this topic in the comments section below 👇 We would be happy to hear and discuss the same 🙂
2 thoughts on “Java 8 Features: How to Use Lambda Expressions”
Very nice. Your posts are really helpful. It contains all the required information and links. Keep it up!! ☺️
Thank you for your feedback. 🙂