Java Lambda : Beginners Guide

This article explains Java Lambda expressions in Java 8. You can find complete code here.

Java Lambda Expressions

Java Lambda Expression is a new and important feature of Java, introduced in Java 8. A Lambda Expression is an anonymous function (a function without name) which doesn’t belong to any class, means a function which doesn’t have a name and doesn’t have a class. Lambda Expression simplified the development a lot by facilitating functional programming in Java. It is used to provide implementation of functional interface (functional interface is an interface that contains only one method. For example, Java standard Runnable interface is a functional interface). It also helps to iterate, filter and extract data from collection libraries. Lambda Expressions enable you to treat code as data and functionality as a method argument.

Syntax of Lambda Expression

Let’s discuss syntax of Lambda Expression.

A Lambda Expression consist of three components, a set of parameters, a Lambda operator and a function body. Here are the three components

  • Parameter List: Here comes argument which can be empty or non empty as well.
  • Lambda Expression: Lambda Expression or arrow(->) is used to separate parameter list and function body.
  • Function body: It contains function statement for Lambda Expression.

Input parameters are on the left side of lambda operator and function body on the right side of lambda operator. This Lambda Expression syntax reduces bulkiness of code that is five lines of code into one line.

parameter list -> function_body

Characteristics of Lambda Expression

Here are few important characteristics of Lambda Expression.

  • Type declaration: Type declaration is optional. Its up to you, if you will not declare type of parameter, compiler can guess from the value of parameter. For example you can write
(5,4) -> function body
  • Parenthesis around parameter: Parenthesis around parameter are also optional. You can put parenthesis if you want, else leave it as it is. If there are multiple parameters in a Lambda Expression then parenthesis are required as shown in above example. For one parameter you can write as
5 -> function body
  • Curly braces: Curly braces around function body is also optional if there is only one statement. For multiple statements curly braces around function body are required. For example
(5, 4) -> 5+4;
  • Return statement: Return statement is also optional in Lambda Expressions. Java compiler automatically returns value if the body has a single expression. If function body returns a value then you should enclose it with curly braces.

Examples of Lambda Expression

Here are few examples of Lambda Expressions.

x, y -> x+y;

The above written Lambda Expression means given two integer x, y and return another integer with the sum of x and y.

Another one

( ) -> 42

The above written Lambda Expression means given no integer and returns integer 42.

Prerequisite

To run Java Lambda Expression following are the prerequisites for it.

  • Java Development Kit (JDK8)
  • NetBeans or Eclipse

Java Lambda Expression with No Parameter

In this example I will show how to use Java Lambda Expressions with no parameter. Open your IDE(I would be using Eclipse Neon) and start creating a new project. Name it as Lambda. Create a class called NoParameter.

public class NoParameter {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
     // lambda expression with return type 
    NoParameterInterface message = () -> {
    		return "Hello World with No Parameter";
    	};
        System.out.println( message.HelloWorld( ));
  }

}

@FunctionalInterface
interface NoParameterInterface {

  //Here is a method with no parameter and return type as String
    public String HelloWorld();
}

The above example shows a hello world message by using a Lambda Expression with no parameter.

Lambda Expression with Single Parameter

You have seen example of Lambda Expression with no parameter. Let’s examine an example of Lambda Expression with single parameter. For this create a class named SingleParameter and paste the following code there.

public class SingleParameter {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
     // lambda expression with single parameter num and returns square of num without any return statement 
    SingleParameterInterface Square = (num) -> num*num;
        System.out.println(Square.SquareOfFive(5));
  }

}


@FunctionalInterface
interface SingleParameterInterface {

  //A method with single parameter and return type as int 
    public int SquareOfFive(int s);
}

 

This above example shows Lambda Expression with single parameter. It takes 5 as an input and returns square of 5 without any return statement. As mentioned above if there is only one statement then no need to specify return keyword. Compiler automatically do returns that value.

Java Lambda Expressions with Multiple Parameters

Let’s do an example of Java Lambda Expression with multiple parameters involved. Create a new java class and name it as MulipleParamater. Open it and paste the following code in it.

public class MulipleParamater {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    //lambda expression which add two number
    MulipleParamaterInterface add = (a, b) -> a + b;
        System.out.println("Sum of 5 and 4 is: "+add.sum(5, 4));
  }

}


interface MulipleParamaterInterface {

  //here is a method with multiple parameter and int as return type 
    public int sum(int a, int b);
}

 

This above example shows Lambda Expression with multiple parameters. It takes 5 and 4 as input and returns sum as 9. Again it works without specifying return keyword.

Event Listener

Let’s explore some more advance examples that is event listener in java. How Lambda Expressions are used to implement event listener. You will see both examples of event listeners with Lambda Expressions and without Lambda Expressions.

Event Listener without Lambda Expressions

First examine event listener without Lambda Expressions. Go to eclipse and create a new class, name it as eListener. Open it and paste the following code.

import java.awt.event.*;		//import for event listener
import javax.swing.JButton;   	//import for JButton class
import javax.swing.JFrame;    	//import for JFrame class
import javax.swing.JTextField;  //import for JTextField 

public class eListener {  
  //event listener class without Lambda Expressions
  static JTextField textfield;
  static JButton button;
  static JFrame frame;
  
    public static void main(String[] args) {  
        textfield=new JTextField(); 
        button=new JButton("click");  
        frame=new JFrame("Event Listener without using Lambda Expression"); 
        
        //set positions of text field and button
        textfield.setBounds(50, 50,150,20);         
        button.setBounds(80,100,70,30);  
        
        //action listener on button 
        button.addActionListener(new ActionListener(){
        	  public void actionPerformed(ActionEvent e){  
        		  textfield.setText("hello world");
        	  }
          });
       
        frame.add(textfield);
        frame.add(button);  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        frame.setLayout(null);  
        frame.setSize(300, 200);  
        frame.setVisible(true);  
  
    }  
  
}

 

The above written code shows an example of event listener in Java without using Lambda Expression. That’s why you must be familiar with the code. Simple JButton, JFrame and JTextFields are used. When user clicks on button text field will show hello world message. Here is the output

 

Event Listener with Lambda Expression

Now examine event listener with Lambda Expression. Go to eclipse and create a new class called eListenerLambda. Open it and paste the following code.

import javax.swing.JButton;   	//import for JButton class
import javax.swing.JFrame;    	//import for JFrame class
import javax.swing.JTextField;  //import for JTextField 

public class eListenerLambda {  
  //event listener class without Lambda Expressions
  static JTextField textfield;
  static JButton button;
  static JFrame frame;
  
    public static void main(String[] args) {  
        textfield=new JTextField(); 
        button=new JButton("click");  
        frame=new JFrame("Event Listener without using Lambda Expression"); 
        
        //set positions of text field and button
        textfield.setBounds(50, 50,150,20);         
        button.setBounds(80,100,70,30);  
          
        // lambda expression implementing here.  
        button.addActionListener(e-> {textfield.setText("hello world");});  
          
         
        frame.add(textfield);
        frame.add(button);  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        frame.setLayout(null);  
        frame.setSize(300, 200);  
        frame.setVisible(true);  
  
    }  
  
}

The above written code shows an example of Java event listener with Lambda Expression. If we compare both codes, you will examine the action listener code in first example has three statements while with Lambda Expression it solved the problem in one statement. The output of both codes is same as shown above.

Comparator Example Using Lambda Expression

Let’s examine one more piece of code that is comparator example with using Lambda Expression. Create a new class and name it as Comparatorlambda.java. Open it and paste the following code.

import java.util.ArrayList;  
import java.util.Collections;  
import java.util.List;  

//account class holds the details of a bank account of customers like account number, name and account balance
class Account{  
    int accountNumber;  
    String name;  
    float AccountBalance;  
    public Account(int accountNumber, String name, float AccountBalance) {  
        super();  
        this.accountNumber = accountNumber;  
        this.name = name;  
        this.AccountBalance = AccountBalance;  
    }  
}  

//comparator class using Lambda Expressions
public class Comparatorlambda{  
  
    public static void main(String[] args) {  
        List<Account> list=new ArrayList<Account>();  
          
        //Adding account details in list  
        list.add(new Account(00235,"Harry",25000));  
        list.add(new Account(11687,"Donald",30088));  
        list.add(new Account(27865,"Caristano",15078));  
          
        System.out.println("Sorting on the basis of account name...");  
  
        // implementing lambda expression  
        Collections.sort(list,(p1,p2)->{  
        return p1.name.compareTo(p2.name);  
        
        });  
        System.out.println("Account Number: Account Name: Account Balance:"); 
        for(Account p:list){  
            System.out.println(p.accountNumber+" \t\t"+p.name+" \t\t"+p.AccountBalance);  
        }  
  
    }  
}

This example has an account class which holds accounts information like name, number and account balance. Lambda Expressions are used to compare and sort accounts on the basis of account name. Here is Lambda Expression used for this purpose.

Collections.sort(list,(p1,p2)->{return p1.name.compareTo(p2.name); });

Following is the output of this code

Conclusion

Lambda Expressions are used to define inline implementation of functional interface. You have seen in the above examples that Lambda Expressions saved our time and reduced the code statements a lot. It gives powerful capabilities to java by facilitating functional programing. This new feature of java has changed the complete way of coding and simplified development as it takes advantage of parallel capabilities of multicore environment.

Leave A Comment

Your email address will not be published. Required fields are marked *