A small introduction to lambdas in Java
Lambdas are introduced in Java 8.
They can be used with functional interfaces.
What is a functional interface ?
Interfaces having single abstract method are called Functional Interfaces.
When I said abstract method, you might be thinking why is it explicity said, since from Java 8, static and default methods are also allowed in Java interfaces. So an interface can be created with a combination of abstract, static and default methods.
A functional interface can also be explicitly made one by placing annotation (@FunctionalInterface) above interface and the compiler checks
and validates, if interface has more than 1 abstract method, it throws an error.
Examples of Functional Interfaces:
To create a Comparator to use that for sorting, we would've created a class and implemented Comparator interface and overridden compareTo method.
As in below class MyLambdalessExample.java
https://gist.github.com/037212d47d95db09ef8380d553712f03
Person class is a custom Java class:
https://gist.github.com/aa76231bd70fcedec88d3ac8aadbbcc5
With lambdas, this can be reduced to few lines as below.
() Open and closed parantheses. If the interface function has parameters they have to be mentioned inside the parantheses.
Example: (Person p1, Person p2)
-> The symbol separates lambda header and body.
{
body of lamdba
return ....
}
https://gist.github.com/21e5cbd12ea7190c19f1b3431b3c87ea
In the example class MyLambda1, in line 29:
the lambda can be assigned to a Comparator variable and it can be re-used at other places in class if required.
In line 25, I used type Person before parameters p1 and p2, but since we are using this Comparator on a list of type Person, we can
get rid of type and instead it can used as in line 29 without type Person.
If the function of the interface has a return type and lambda has more than 1 line, return statement is mandatory.
If the lambda has multiple parameters it should be used with opening and closing braces as in line 38.
For single line lambda bodies, a return keyword is not required. But for lambdas having multiple lines in the body, return is required as we can see in line 38.