Lambda expression is simply a function without having any name. It can even be used as a parameter in a function. Lambda Expression facilitates functional programming and simplifies the development a lot.
The main use of Lambda expression is to provide an implementation for functional interfaces.
For example, Lambda expression provides an implementation for Printable functional interface
interface Printable {
void print(String msg);
}
public class JLEExampleSingleParameter {
public static void main(String[] args) {
// without lambda expression
Printable printable = new Printable() {
@Override
public void print(String msg) {
System.out.println(msg);
}
};
printable.print(" Print message to console....");
// with lambda expression
Printable withLambda = (msg) -> System.out.println(msg);
withLambda.print(" Print message to console....");
}
}
Output :
Print message to console....
Print message to console....
Example 2, Create a method that takes a lambda expression as a parameter:
interface StringFunction {
String run(String str);
}
public class Main {
public static void main(String[] args) {
StringFunction exclaim = (s) -> s + "!";
StringFunction ask = (s) -> s + "?";
printFormatted("Hello", exclaim);
printFormatted("Hello", ask);
}
public static void printFormatted(String str, StringFunction format) {
String result = format.run(str);
System.out.println(result);
}
}
Example 3, Pass lambda expression as an argument to the constructor
static Runnable runnableLambda = () -> {
System.out.println("Runnable Task 1");
System.out.println("Runnable Task 2");
};
//Pass lambda expression as argument
new Thread(runnableLambda).start();