Lambda Expression in Java 8

Lambda expressions in Java are a relatively new feature that was introduced in Java 8. It’s an important feature of functional programming in Java. Lambda expressions are a concise way to represent a function interface using a compact block of code. It simplifies the process of working with interfaces that contain only one method, known as functional interfaces. This blog post will provide a detailed overview of lambda expressions in Java.

What are Lambda Expressions?
A lambda expression is a compact block of code that represents an anonymous function. It allows you to pass behavior as a parameter to a method or constructor. In other words, lambda expressions allow you to treat functionality as data. A lambda expression consists of three parts:

Parameters: It represents the input that a function receives.
Arrow operator: “->” separates the parameters and the body of the lambda expression.
Body: It represents the behavior of the function.
Syntax
The syntax of a lambda expression is as follows:
(parameter1, parameter2, parameter3, …) -> { code block }

For example, let’s define a lambda expression that takes two integers as parameters and returns their sum:
(int a, int b) -> { return a + b; }

Functional Interfaces
Lambda expressions work with functional interfaces, which are interfaces that contain only one abstract method. The annotation @FunctionalInterface can be used to ensure that the interface is a functional interface. The functional interface provides a single abstract method that represents the behavior of the lambda expression.

Example:

@FunctionalInterface
interface MyFunctionalInterface {
    public int performAction(int a, int b);
}

Using Lambda Expressions
To use a lambda expression, we need to follow three steps:

Define the functional interface.
Define the lambda expression.
Pass the lambda expression to the method or constructor.
Here’s an example that demonstrates the use of lambda expressions in Java:

// Define a functional interface
@FunctionalInterface
interface MyFunctionalInterface {
    public int performAction(int a, int b);
}

public class LambdaExample {
    public static void main(String[] args) {
        // Define a lambda expression
        MyFunctionalInterface sum = (a, b) -> a + b;

         // Pass the lambda expression to the method
         int result = doAction(5, 10, sum);
         System.out.println(result);
}

public static int doAction(int a, int b, MyFunctionalInterface myFunctionalInterface) {
        return myFunctionalInterface.performAction(a, b);
}
}

Output: 15

Conclusion
Lambda expressions are a powerful feature of Java 8 that simplify the process of working with functional interfaces. They provide a concise way to represent behavior as data, making it easy to pass functionality as a parameter to a method or constructor. Lambda expressions are an important tool for developers who want to write clean, concise, and expressive code.

1 Comment

Comments are closed