Lambda expressions in Java

Lambda expressions is a new feature introduced in Java 8. Lambda expressions are used to create instances (‘Instance’ is creation of object) of functional interfaces. A functional interface is basically an interface with single abstract method( For example Runnable, callable, ActionListener etc).A lambda expression can be expressed as an anonymous function that doesn’t have a name and doesn’t belong to any class. The concept of lambda expression was first introduced in LISP programming language.

Lambda expression syntax:

To create a lambda expression we specify input parameters (if there are any) on the left side of the lambda operator “ ->” and place the expression or block of statements on the right side of the lambda operator.

//syntax of lambda expression

(parameter_list) -> (function_body);

For example, the lambda expression (x, y) -> x + y specifies that lambda expression takes two arguments x and y and returns the sum of these.

Lambda expression with zero parameter:
interface FunctionalInterfaceEx1 {

//A method with zero parameter
public String sayHello();
}
public class SampleTest{

public static void main(String args[]) {
// lambda expression returning some message
FunctionalInterfaceEx1 message = () -> {
return "Hello World!";
};
System.out.println(message.sayHello());
}
}

Output:

Hello World!

Lambda expression with one parameter:

// Java program to demonstrate lambda expressions 
// to implement a user defined functional interface. 
// A sample functional interface 
interface FuncInterface 
{ 
//An abstract function
void abstractFun(int x);
// A non-abstract function 
default void sampleFun() 
  { 
    System.out.println("Good Luck!"); 
  } 
} 

class SampleTest1
{ 
    public static void main(String args[]) 
    { 
       // lambda expression to implement above functional interface. This interface //by default implements abstractFun() 
FuncInterface funinterfaceObj= (int x)->System.out.println("The square of "+x+" is "+x*x);
      // This calls above lambda expression. 
      funinterfaceObj.abstractFun(10);
    } 
} 

Output:

The square of 10 is 100

Lambda expression with two parameters:
interface nums {

    public int res(int a, int b);
}

public class SampleTest2{

   public static void main(String args[]) {
        // lambda expression with multiple arguments
    	nums add1 = (n1, n2) -> n1 + n2;
	System.out.println("The Sum is : "+add1.res(30,20));
	nums mul1 = (n1,n2) -> n1*n2;
	System.out.println("The Multiplication result is : "+mul1.res(2,5));
        nums sub1 = (n1,n2) -> { if (n1>n2) n1-n2;else n2-n1;}
	System.out.println("The Difference is : "+sub1.res(10,20));
	
    }
}

Output:

The Sum is 50
The Multiplication result is 10
The Difference is 10

Comparing the older version with new version to implement action listeners using lambDa operator:
Prior to Java 8:
import java.awt.*;  
import java.awt.event.*;  
public class ButtonListenerPrior8 {  
    public static void main(String[] args) {  
       Frame frame=new Frame("ActionListener Prior Java8");  
    
       Button b=new Button("Click Here");  
       b.setBounds(50,100,80,50);  
  
       b.addActionListener(new ActionListener(){  
          public void actionPerformed(ActionEvent e){  
    	     System.out.println("Hello! have a good day"); 
          }  
       });  
       frame.add(b);
    
       frame.setSize(200,200);  
       frame.setLayout(null);  
       frame.setVisible(true);   
    }  
}
In Java 8 with lambda operator:

import java.awt.*;  
public class ButtonListenerPost8 {  
   public static void main(String[] args) {  
      Frame frame=new Frame("ActionListener java8");  
     
      Button b=new Button("Click Here");  
      b.setBounds(50,100,80,50); 
  
      b.addActionListener(e -> System.out.println("Hello! Have a good day")); 
      frame.add(b);
  
      frame.setSize(200,200);  
      frame.setLayout(null);  
      frame.setVisible(true);   
   }  
}
Iterating through list using foreach lambda expression:

import java.util.*;  
public class SampleTest3{  
    public static void main(String[] args) {       
       List<String> list=new ArrayList<String>();  
       list.add("Nikhil");         
       list.add("Divya");       
       list.add("Nikitha");         
       list.add("Manisha");         
       list.add("Deepak");                
       list.forEach(          
           // lambda expression        
           (students)->System.out.println(students)         
       );     
    }  
}

Output:

Nikhil
Divya
Nikitha
Manisha
Deepak

Notes:

1.The lambda expressions can be used with the existing API even when your project is migrated to Java 8.
2.The code is compressed to few lines with lambda expression.
3.Easy implementation of functional interface with the lambda operator.

React JS Automation Frameworks Insights
0