What is a Lambda Expression in Java?

What is a Lambda Expression?

A Lambda Expression is a short and clean way to represent a block of code that can be passed around and executed later.

It was introduced in Java 8 to make programming easier and more expressive, especially when working with functional interfaces

Before lambda expressions, if you wanted to implement a small piece of logic using an interface, you had to create anonymous inner classes.

Syntax of Lambda Expression:

(parameter_list) -> { body_of_expression }

Components of Lambda Expressions

Lambda expressions make Java programming cleaner and faster by reducing unnecessary code.

1) Parameters: These are the input values passed into the lambda expression, similar to method parameters.

  • If there is only one parameter, parentheses () can be skipped.
  • If there are multiple parameters, they must be enclosed in parentheses.

Example:

(a, b) -> a + b
  • Here, a and b are parameters.

2) Arrow Operator (->): The arrow operator -> separates the parameters from the body of the lambda expression.

3) Body: The body is the part after the arrow operator. It contains the logic that will execute when the lambda is called.

Example:

() -> System.out.println("Hello from Lambda!");

    Functional Interfaces and Lambda Expressions

    A functional interface is an interface with only one abstract method. Lambda expressions can directly implement these interfaces.

    Example of Functional Interface

    @FunctionalInterface
    interface Calculator {
    int calculate(int a, int b); // Single abstract method
    }

    Using Lambda with Functional Interface

    public class LambdaExample {
    public static void main(String[] args) {
    // Lambda for addition
    Calculator add = (a, b) -> a + b;
    System.out.println("Addition: " + add.calculate(10, 20));

    // Lambda for multiplication
    Calculator multiply = (a, b) -> a * b;
    System.out.println("Multiplication: " + multiply.calculate(5, 4));

    // Lambda for subtraction (extra unique example)
    Calculator subtract = (a, b) -> a - b;
    System.out.println("Subtraction: " + subtract.calculate(25, 5));
    }
    }

    Output:

    Addition: 30
    Multiplication: 20
    Subtraction: 20

    Key Features of Lambda Expressions

    Lambda expressions were introduced in Java 8 to make code shorter, cleaner, and easier to understand.

    1) No Name: Lambdas are nameless functions. they don’t need a method name or belong to a specific class. They are defined and used instantly, often for short operations.

    Example:

    Runnable task = () -> System.out.println("Task running without a name!");
    task.run();

    2) No Return Type: You don’t need to specify a return type in lambda expressions. The Java compiler automatically infers (detects) it from the expression body.

    Example:

    // The compiler understands that this returns an int
    Calculator add = (a, b) -> a + b;

    Here, Java knows the result will be an integer because both a and b are integers.

    3) Simplified Syntax: Lambda syntax is short and elegant. It eliminates unnecessary code like method names, modifiers, or even braces in simple cases.

    Single Statement:

    When the body has only one line, braces {} and return are not required.

    Comparator<Integer> compare = (a, b) -> a - b;

    Multiple Statements:

    If your logic has more than one line, you must use {} and explicitly return a value.

    Comparator<Integer> detailedCompare = (a, b) -> {
        System.out.println("Comparing " + a + " and " + b);
        return a - b;
    };

      Lambda Expressions in Streams

      Lambda expressions are commonly used in conjunction with the Streams API to process collections.

      Example:

      import java.util.Arrays;
      import java.util.List;

      public class LambdaStreamExample {
      public static void main(String[] args) {
      List<String> names = Arrays.asList("Aarav", "Riya", "Ankit", "Priya", "Arjun");

      // Filter names that start with 'A'
      System.out.println("Names starting with 'A':");
      names.stream()
      .filter(name -> name.startsWith("A"))
      .forEach(System.out::println);

      // Convert all names to uppercase
      System.out.println("\nNames in uppercase:");
      names.stream()
      .map(name -> name.toUpperCase())
      .forEach(System.out::println);

      // Count names having more than 4 letters
      long count = names.stream()
      .filter(name -> name.length() > 4)
      .count();
      System.out.println("\nNames with more than 4 letters: " + count);
      }
      }

      Output:

      Names starting with 'A':
      Aarav
      Ankit
      Arjun

      Names in uppercase:
      AARAV
      RIYA
      ANKIT
      PRIYA
      ARJUN

      Names with more than 4 letters: 3

      Also Learn Important Topics of Java

      Leave a Comment