Skip to main content
Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming, and simplifies the development a lot.

Syntax

A lambda expression is characterized by the following syntax −
parameter -> expression body
Following are the important characteristics of a lambda expression −
  • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
  • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
  • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.

Lambda Expressions Example

Create the following Java program using editor and save in some folder like C:\>JAVA.

Java8Tester.java

public class Java8Tester {
   public static void main(String args[]){
      Java8Tester tester = new Java8Tester();
  
      //with type declaration
      MathOperation addition = (int a, int b) -> a + b;
  
      //with out type declaration
      MathOperation subtraction = (a, b) -> a - b;
  
      //with return statement along with curly braces
      MathOperation multiplication = (int a, int b) -> { return a * b; };
  
      //without return statement and without curly braces
      MathOperation division = (int a, int b) -> a / b;
  
      System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
      System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
      System.out.println("10 / 5 = " + tester.operate(10, 5, division));
  
      //with parenthesis
      GreetingService greetService1 = message ->
      System.out.println("Hello " + message);
  
      //without parenthesis
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
  
      greetService1.sayMessage("Mahesh");
      greetService2.sayMessage("Suresh");
   }
 
   interface MathOperation {
      int operation(int a, int b);
   }
 
   interface GreetingService {
      void sayMessage(String message);
   }
 
   private int operate(int a, int b, MathOperation mathOperation){
      return mathOperation.operation(a, b);
   }
}

Verify the Result

Compile the class using javac compiler as follows −
$javac Java8Tester.java
Now run the Java8Tester as follows −
$java Java8Tester
It should produce the following output −
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh
Following are the important points to be considered in the above example.
  • Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.
  • Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.

Scope

Using lambda expression, you can refer to final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time.

Scope Example

Create the following Java program using editor and save in some folder like C:\>JAVA.
Java8Tester.java
public class Java8Tester {

   final static String salutation = "Hello! ";
   
   public static void main(String args[]){
      GreetingService greetService1 = message -> 
      System.out.println(salutation + message);
      greetService1.sayMessage("Mahesh");
   }
 
   interface GreetingService {
      void sayMessage(String message);
   }
}

Verify the Result

Compile the class using javac compiler as follows −
$javac Java8Tester.java
Now run the Java8Tester as follows −
$java Java8Tester
It should produce the following output −
Hello! Mahesh

Comments

Popular posts from this blog

In this chapter, we will see how to enable remote desktop application. It is important because this enables us to work remotely on the server. To do this, we have the following two options. For the first option, we have to follow the steps given below. Step 1  − Go to Start → right click “This PC” → Properties. Step 2  − On Left side click “Remote Setting”. Step 3  − Check radio button “Allow Remote connection to this computer” and Check box “Allow connection only from computers running Remote Desktop with Network Level Authentication (recommended)” → click “Select Users”. Step 4  − Click Add. Step 5  − Type user that you want to allow access. In my case, it is administrator → click OK. For the  second option , we need to follow the steps given below. Step 1  − Click on “Server Manage” → Local Server → click on “Enable” or Disable, if it is Disabled.
The table creation command requires: Name of the table Names of fields Definitions for each field Syntax: Here is generic SQL syntax to create a MySQL table: CREATE TABLE table_name ( column_name column_type ); Now, we will create following table in  TUTORIALS  database. tutorials_tbl ( tutorial_id INT NOT NULL AUTO_INCREMENT , tutorial_title VARCHAR ( 100 ) NOT NULL , tutorial_author VARCHAR ( 40 ) NOT NULL , submission_date DATE , PRIMARY KEY ( tutorial_id ) ); Here few items need explanation: Field Attribute  NOT NULL  is being used because we do not want this field to be NULL. So if user will try to create a record with NULL value, then MySQL will raise an error. Field Attribute  AUTO_INCREMENT  tells MySQL to go ahead and add the next available number to the id field. Keyword  PRIMARY KEY  is used to define a column as primary key. You can use multiple columns separated by comma to define...
The Windows Firewall with Advanced Security is a firewall that runs on the Windows Server 2012 and is turned on by default. The Firewall settings within Windows Server 2012 are managed from within the  Windows Firewall Microsoft Management Console . To set Firewall settings perform the following steps − Step 1  − Click on the Server Manager from the task bar → Click the Tools menu and select Windows Firewall with Advanced Security. Step 2  − To see the current configuration settings by selecting  Windows Firewall Properties  from the MMC. This  allows access to modify the settings  for each of the three firewall profiles, which are –  Domain, Private and Public  and IPsec settings. Step 3  − Applying custom rules, which will include the following two steps − Select either  Inbound Rules  or  Outbound Rules  under  Windows Firewall with Advanced Security  on the left side of the management console...