Hello Folks,
Today I'm sharing my basic learning to Lambda Expressions.
Today I'm sharing my basic learning to Lambda Expressions.
Lambda
Expression
Functional Interfaces: Java 8 intoduced one new Terminology to
distinguish interfaces, those intefraces having having only one
method.
Lambda
Expression are functional only for Functional Interfaces for example
Runnable
Interface,ActionListener
etc.
Lambda used the concept of anonymous inner classes objects.
Syntax
of lambda expression
()-> for a single statement
()->{} for multiple line of codes.
Example:
One
Line Statement:
public class Runns{
public static void main(String... args){
Runnable
r=()->System.out.println("Hi Pratik"); //overriding
the one and only method i.e. run
Thread t1=new Thread(r);
t1.start();
}
}
Multiple
Line Code:
public class Runns{
public static void main(String... args){
Runnable
r=()->{ //overriding
the one and only method i.e. run
try{
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
}
}
catch(InterruptedException e){
e.printStackTrace();
}
};
Thread t1=new Thread(r,"Nile Thread");
t1.start();
}
}
Here what we did is creation of a anonymous inner class implementing
Runnable interface, and handed it over the Thread's object.
As earlier said lambda works on functional interfaces i.e. having
only one method, it it does not to worry about multiple methods, it
simply overrides the one and only method.
Thank You :)