Java Lambda Expressions

Introduction to Lambda Expressions in Java

Lambda expressions, also known as arrow functions, are a concise way to write anonymous functions in Java. They were introduced in Java 8 and have become a popular feature for writing functional code.

Lambda expressions are defined using the following syntax:


(parameters) -> expression

The parameters are a comma-separated list of types or variable names, and the expression is the body of the function. The body of the function can be any valid Java code, including multiple statements.

For example, the following lambda expression is equivalent to the following anonymous inner class:


// Lambda expression
(String s) -> s.toUpperCase()

// Anonymous inner class
new Function() {
  @Override
  public String apply(String s) {
    return s.toUpperCase();
  }
};

Lambda expressions can be used in a variety of ways, such as:

  • Passing them as arguments to methods
  • Using them as part of stream operations
  • Creating event handlers
  • Implementing functional interfaces

Lambda expressions can make your code more concise and expressive, and they can help you to write more functional code. They are a powerful tool for writing efficient and maintainable Java code.

Exercises

Code for creation of an object using a lambda expression.


  package practiceproject;
  import java.io.*;
  public class democlass{
    
      public static void main(String[] args){
          
      employee e = ()->{System.out.println("I am the Professor");};
      e.display();
      }
  }
  
  //an interface with only one abstract method is called functional interface
  //we can provide the implementation for an functional interface without using a 
  //anonymous class
  interface employee
  {
    void display();
  } 

Code for demonstrating the use of lamda expressions with parameters


  package practiceproject;
  import java.io.*;
  public class democlass{
    
      public static void main(String[] args){
      employee e = (name,designation)->{System.out.println("I am the Professor "+name+ "and designation is"+ designation);};
      e.display("satish","Professor");
      }
  }
  
  interface employee
  {
    void display(String name,String designation);
  } 

Code for demonstrating the use of lamda expressions with parameters and a return value


  package practiceproject;
  import java.io.*;
  public class democlass{
    
      public static void main(String[] args){
      employee e = (a,b)->{return a+b;};
      int result = e.display(3, 2);
      System.out.println(result);
      }
  }
  
  interface employee
  {
    int display(int a,int b);
  } 

Code for creating a thread using a Lambda Expression


  package practiceproject;
  import java.io.*;
  public class democlass{
    
      public static void main(String[] args){
      Runnable R2 = ()->{System.out.println("I am from thread1");};
      Thread t2 = new Thread(R2);
      t2.start();
      }
  }