Java Lambda Expression Syntax and Features

Java 8 introduced Lambda Expressions, a new language feature that can be viewed as anonymous functions. These can be passed to methods as arguments or stored in variables for later use.

The syntax of a Lambda Expression is as follows:
(parameter1, parameter2, ...) -> { function_body }

In this syntax:

  • parameter1, parameter2, etc., represent the parameter list of the Lambda Expression, which can consist of zero or more parameters.
  • function_body represents the body of the Lambda Expression, which can be either a single expression or a block of code.

The primary characteristics of Lambda Expressions include:

  1. They can be viewed as implementations of functional interfaces, i.e., interfaces with only one abstract method.
  2. Parameter types can be automatically inferred through type inference.
  3. They have direct access to local variables that are final or effectively final.
  4. They allow the use of method references to simplify code.

The use of Lambda Expressions simplifies code, enhancing readability and maintainability. Common usage scenarios include collection operations, thread processing, and GUI programming.

Examples

Below is a simple example of a Lambda Expression used to implement an abstract method within an interface:

interface MathOperation {
   int operate(int a, int b);
}
public class LambdaExample {
   public static void main(String args[]) {
      // Implement the abstract method of the MathOperation interface using a Lambda Expression
      MathOperation addition = (int a, int b) -> a + b;
      // Invoke the implementation method of the MathOperation interface
      int sum = addition.operate(10, 5);
      System.out.println("10 + 5 = " + sum);
   }
}

In the example above, a functional interface MathOperation is defined, containing an abstract method operate. This method accepts two integer parameters and returns an integer.

Next, within the main method, the abstract method of this interface is implemented using a Lambda Expression. The implementation uses the a + b expression to calculate the sum of the two parameters.

Finally, the method addition.operate(10, 5) is invoked, yielding a result of 15, which is then printed to the console.