2- Lamda Expression

 What is Lamda expression and its need?

Lambda Expressions were added in Java 8.

A lambda expression is a short block of code which takes in parameters and returns a value.

 Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

OR

Expression through which we can represent anonymous(nameless) function.


Syntax: 

( argument-list )   ->  {body} 


Argument-list : It can be empty or non-empty as well.

 Arrow-token : It is used to link arguments-list and body of expression.

 Body : It contains expressions and statements for lambda expression. 


WRITE A PIECE OF JAVA CODE USING LAMDA EXPRESSION

/*
--> Anonymous class is an inner class without a name, which means that
    we can declare and instantiate class at the same time.

--> A lambda expression is a short form for writing an anonymous class.
--> By using a lambda expression, we can declare methods without any name
 
 Write a code using two interfaces similar in working but
 --> Use anonymous class to implement first interface  &
 --> Use lambda expression to implement another interface
 */



package com.company;

interface Run{
    void speed(int a);
   
}
interface Walk{
    void walking(int b);
}


public class AdvanceJava_AnonymousClass_LambdaExpression {

    public static void main(String[] args) {
   
    //Using Anonymous Class without lambda expression
      Walk w= new Walk() {  
             public void walking(int b) {
             System.out.println("You are running at: "+b+" m/s");
              }
        };
    w.walking(2);  
         
       
    //Using Anonymous Class WITH lambda expression  
    Run r1 = (a)->{System.out.println("You are running at: "+a+" m/s");};
   
     r1.speed(13);
   
   
    }
}

Comments

Popular posts from this blog

INDEX OF JAVA 8 and MICROSERVICES BLOG