Lecture on Lambda Expressions

Jun 22, 2024

Lecture on Lambda Expressions

Overview

  • Lambda Expressions: A feature to simplify the code of anonymous inner classes, introduced in Java.

Functional Interface

  • Concept: Interfaces with only one abstract method.
  • Example: Interface A with method show().
    interface A { 
        void show(); 
    }
    

Traditional Anonymous Inner Class

  • Instantiation: Normally, you instantiate a class implementing an interface with an anonymous inner class.
    A obj = new A() { 
        public void show() { 
            // method implementation 
        } 
    };
    

Using Lambda Expressions

  • Simplification: Reduce the verbosity of anonymous inner classes.
  • Syntax: Replaces the need to declare the method and the unnecessary overhead.
    A obj = () -> { 
        // method implementation 
    };
    
    • Arrow Token (->): Key part of Lambda syntax.

Reduction and Syntactic Sugar

  • Without Curly Braces: If the method contains only one statement.
    A obj = () -> System.out.println("Show method");
    
  • Benefits: Cleaner and shorter code.

Lambda Expressions with Parameters

  • Method with Parameters: If show accepts an integer parameter.
    interface A {
        void show(int i);
    }
    
    • Anonymous Inner Class:
      A obj = new A() { 
          public void show(int i) { 
              System.out.println("Value: " + i); 
          } 
      };
      
    • Lambda Expression: Simplified version accepting a parameter.
      A obj = (int i) -> System.out.println("Value: " + i);
      

Removing Variable Type and Parentheses

  • Type Inference: Java infers the type from the interface declaration.
    A obj = (i) -> System.out.println("Value: " + i);
    
  • Single Parameter Simplification: Parentheses can be omitted when there's only one parameter.
    A obj = i -> System.out.println("Value: " + i);
    

Compilation and Class Files

  • Class File Management: Lambda expressions reduce the number of generated class files but may increase the size of the .java file.

Next Steps

  • Return Types and Multiple Parameters: To be covered in the next video.