Great Deals

java8 lambda

20:02 suresh chaudhari 0 Comments




What is lambda Expressions?


                  The lambda expression is just like the function it consist of


  • List of parameters
  • Method Body
  • return Type


Lambda Expression termed as anonymous because it does not have any name.
Lambda Expression passed as arguments to the methods.


Anatomy of Lambda expression :)

Yes guys you heard it right we are going to do the dissection of the Lambda Expression.

Lambda expression=Parameters+Arrow+Method Body

(Car c1,Car 2)   ->      c1.getPrice().comparTo(c2.getPrice());

Please have a look at the below code snippets where i have compared codes of Java7 and Java8

Example 1
Using Java7

Comparator<Car> byPrice=new Comparator<Car>(){

Public int compare(Car c1,Car c2){

    return c1.getPrice().compareTo(c2.getPrice());

}

};

By Lambda Expressions
Using Java8


Comparator<Car> byPrice=(Car c1,Car c2)--->c1.getPrice().compareTo(c2.getPrice());

Example 2

Java7
class A implements Runnable
{
       public void run()
     {
                System.out.println("I am Java7");
      }
}

By Lambda Expression
Java8

()->{System.out.println("I am Java8");}


Advantage of Lambda Interface:

Cleaner Code:Lambdas are your code much easier to read.

0 comments:

Advertising