Lambda Expression
Lambda Expression
==========================
Lambda expression is a new and important feature of Java which was included
in Java SE 8.
It provides a clear and concise way to represent one method interface using an
expression. It is
very useful in collection library. It helps to iterate, filter and extract data
from collection.
Functional Interface:
---------------------------
No Parameter Syntax:
----------------------
() -> {
//Body of no parameter lambda
}
interface Drawable{
public void draw();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
int width=10;
};
d.draw();
}
}
interface Sayable{
public String say();
}
public class LambdaExpressionExample3{
public static void main(String[] args) {
Sayable s=()->{
return "I have nothing to say.";
};
System.out.println(s.say());
}
}
Java Lambda Expression Example: Single Parameter:
----------------------------------------------------
interface Sayable{
public String say(String name);
}
In Java lambda expression, if there is only one statement, you may or may not use
return keyword.
You must use return keyword when lambda expression contains multiple statements.
interface Addable{
int add(int a,int b);
}
@FunctionalInterface
interface Sayable{
String say(String message);
}
we can use lambda expression to run thread. In the following example, we are
implementing run
method by using lambda expression.
import java.util.*;
class Product{
int id;
String name;
double price;
public Product(int id, String name, float price) {
this.id = id;
this.name = name;
this.price = price;
}
}
public class LambdaExpressionExample10{
public static void main(String[] args) {
List<Product> list=new ArrayList<Product>();
//Adding Products
list.add(new Product(1,"HP Laptop",25000));
list.add(new Product(3,"Keyboard",300));
list.add(new Product(2,"Dell Mouse",150));
}
}