Home » Lambda expression in java

Lambda expression in java

Lambda expression in java

Lambda expressions were introduced in Java 8 and were touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming and simplifies development a lot. A lambda expression works on the principle of functional interface. A Functional interface is an interface with only one method  to implement. A lambda expression provides an implementation of the functional interface method.

Lambda expression simplifies functional programming a lot and makes code readable without any boilerplate code. A lambda expression can infer the type of parameter used and can return a value without a return keyword. In the case of the simple one-statement method, even curly braces can be eliminated.

There are various reasons for addition of lambda expression in Java platform but the most beneficial of them is that we can easily distribute processing of collection over multiple threads. Prior to Java 8, if the processing of elements in a collection had to be done in parallel, the client code was supposed to perform the necessary steps and not the collection. In Java 8, using lambda expression and Stream API we can pass processing logic of elements into methods provided by collections and now collection is responsible for parallel processing of elements and not the client.

Lambda expression feature

Lambda expression in Java is a feature introduced in Java 8 that allows you to implement one-function interfaces (functional interfaces) more simply and concisely. It is an anonymous function that adds functional programming techniques to Java, making it easier to write code in specific situations compared to using anonymous inner classes.

Syntax

(parameter list) -> expression
Java

Or

(parameter list) -> { statements }
Java

Example

// Original approach without lambda expression
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("This is a runnable.");
    }
};

// Using lambda expression
Runnable lambdaRunnable = () -> {
    System.out.println("This is a lambda runnable.");
};

// Another example with a single parameter
Function<Integer, Integer> square = (num) -> num * num;
Java

In the above examples:

  • The first example demonstrates the old approach of implementing the Runnable interface using an anonymous inner class.
  • The second example demonstrates the usage of lambda expression to achieve the same functionality with a much more concise syntax.
  • The third example demonstrates a lambda expression with a single parameter. It calculates the square of the input number.

Functionalities of Lambda Expression in Java

  • Provides a concise way to represent anonymous functions.
  • Allows the representation of single-method interfaces (functional interfaces) more easily.
  • Enables the treatment of functionality as method arguments.
  • Reduces the need for anonymous inner classes when working with functional interfaces.
  • Simplifies code by removing boilerplate code related to interface implementations.
  • Supports the use of functional interfaces directly in-line with method invocation.
  • Enhances readability and maintainability of code by focusing on the behavior rather than the implementation details.
  • Enables the implementation of functional programming concepts, such as higher-order functions and closures, in Java.
  • Can be used with built-in functional interfaces provided by the Java standard library, such as Runnable, Comparator, Function, etc.
  • Facilitates the development of more expressive and declarative code.

Lambda Expression Parameters

There are three Lambda Expression Parameters are mentioned below:

  1. Zero Parameter
  2. Single Parameter
  3. Multiple Parameters

1. Lambda Expression with Zero parameter 

public class LambdaZeroParameter {
    public static void main(String[] args) {
        // Lambda expression with zero parameters
        Runnable zeroParamLambda = () -> {
            System.out.println("This is a lambda expression with zero parameters.");
        };

        // Calling the lambda expression
        zeroParamLambda.run();
    }
}
Java

Output

This is a lambda expression with zero parameters.
Java

 2. Lambda Expression with Single parameter

import java.util.function.Function;

public class LambdaSingleParameter {
    public static void main(String[] args) {
        // Lambda expression with a single parameter
        Function<Integer, Integer> square = (num) -> num * num;

        // Calling the lambda expression
        int result = square.apply(5);
        System.out.println("Square of 5 is: " + result);
    }
}
Java

Output

Square of 5 is: 25
Java

 3. Lambda Expression with Multiple parameters

import java.util.function.BiFunction;

public class LambdaMultipleParameters {
    public static void main(String[] args) {
        // Lambda expression with multiple parameters
        BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;

        // Calling the lambda expression
        int result = add.apply(5, 3);
        System.out.println("Sum of 5 and 3 is: " + result);
    }
}
Java

Output

Sum of 5 and 3 is: 8
Java

Advantages and disadvantages of lambda expressions

Advantages:

  1. Conciseness: Lambda expressions allow for more concise code compared to traditional anonymous inner classes. This reduces boilerplate code and makes the codebase more readable and maintainable.
  2. Expressiveness: They enable developers to express behavior more clearly and directly. By focusing on the functionality rather than the mechanics of implementation, lambda expressions can make code more expressive and easier to understand.
  3. Functional Programming: Lambda expressions facilitate the adoption of functional programming paradigms in Java. They enable the use of higher-order functions, closures, and functional interfaces, allowing developers to write more functional-style code.
  4. Improved Iteration: When working with collections and streams, lambda expressions can be used with functional interfaces like Predicate, Consumer, Function, etc., making iteration and processing of elements more streamlined and expressive.
  5. Ease of Parallelism: Lambda expressions, especially when used with Java Streams API, make it easier to parallelize computations. They provide a more declarative way to express parallel operations on collections, enhancing performance in multi-core environments.

Disadvantages:

  1. Learning Curve: Lambda expressions introduce a new syntax and programming paradigm to Java, which may have a learning curve for developers unfamiliar with functional programming concepts.
  2. Readability: While lambda expressions can make code more concise, they may also reduce readability if overused or if used inappropriately. Complex lambda expressions with multiple statements or deeply nested expressions can be difficult to understand.
  3. Debugging: Debugging lambda expressions can be more challenging compared to traditional methods or anonymous inner classes. Stack traces may not clearly indicate the origin of lambda expressions, making it harder to diagnose issues.
  4. Limited Use Cases: Lambda expressions are most useful when working with functional interfaces and collections. However, there are scenarios where lambda expressions may not be applicable or may not provide significant advantages over traditional approaches.
  5. Tool Support: While modern IDEs provide support for lambda expressions, including syntax highlighting, code completion, and refactoring tools, older tools or versions may not fully support them, leading to compatibility issues in certain environments.

Conclusion

Lambda expressions in Java offer significant advantages, enhancing code conciseness, expressiveness, and support for functional programming. They prioritize behavior over implementation, reducing boilerplate code and boosting maintainability. By embracing functional programming concepts like higher-order functions and closures, they enable developers to write expressive, declarative code. Lambda expressions streamline collection iteration, especially when combined with Java’s Streams API, and facilitate parallel computation in multi-core environments. However, they pose challenges for developers new to functional programming and may lead to readability issues if overused. Despite these challenges, lambda expressions remain a powerful feature, striking a balance between conciseness and readability when used appropriately. They bolster Java’s versatility, enabling developers to craft expressive, maintainable code while embracing modern paradigms. As Java evolves, lambda expressions will likely continue shaping its future and its relevance in modern software development.

Frequently Asked Questions

1. What is a lambda expression in Java?

A lambda expression is a concise way to represent an anonymous function, which can be treated as a method argument or stored in a variable. It enables the implementation of functional programming concepts in Java.

2. How do lambda expressions differ from anonymous inner classes?

Lambda expressions provide a more concise syntax compared to anonymous inner classes. They focus solely on the method’s behavior, while anonymous inner classes include boilerplate code related to class and method definitions.

3. What is a functional interface in Java?

A functional interface is an interface that contains only one abstract method. It serves as the target type for lambda expressions and method references in Java.