As we know that java8 has come up with a lot of new features Lambda Expression is one of them. It will help us in many ways like reduce the boilerplate code and make our code look clean and concise.
Lambda Expression
A Lambda expression is an anonymous function and is expressed as an instance of functional interfaces.
public class DemoLambda {
public static void main(String... a) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(a[0] + " : from New Thread");
}
});
thread.start();
System.out.println(a[0] + " : from main Thread");
}
}
$java DemoLambda “Hello Lambda!!!”
Hello Lambdas!!! : from main Thread
Hello Lambdas!!! : from New Thread
Why we need Lambda Expression and how it helps us in coding?
- Enables Functional Programming:- Lambdas enables us to write functional code.
- Readable and Concise Code:- The boilerplate code can easily be removed using Lambdas.
- Easy-to-Use APIs and Libraries: The APIs designed using Lambda are easier to use and support other APIs.
Functional Interfaces
A Functional Interface is an interface that contains only one abstract method. They can have only single functionality to exhibit.
Functional Interfaces can be annotated with @FunctionalInterface.
- It will cause compilation to fail if a second abstract method is added.
- Annotate your own single Abstract method types with @FunctionalInterface.
@FunctionalInterface
interface Square {
int calculate(int x);
}
Syntax of a Lambda Expression
(Argument List) ->{expression;} or
(Argument List) ->{statements;}
Best practices of using lambda expressions
- Use Predefined Interfaces
- Annotate Functional Interfaces
- Keep Lambdas short
- Don’t include parameter types.
- Avoid return statements, and curly braces where possible.
- We can use lambda expressions for an interface which contains only one abstract methods.
Hope this Blog will help you.
Happy Blogging!!