Lambda Expression in Java (Java 8 Features)

Introduction to Lambda Expressions

  • Lambda expressions are anonymous functions, meaning they do not have a name, return type, or modifiers.
  • The basic structure of a lambda expression involves removing the modifiers, return type, and method name, and placing an arrow between parameters and the body.
api response

Example: Traditional Method vs. Lambda Expression

Traditional method for adding two numbers:


public class LambdaExample {
    public static void main(String[] args) {
        // Using a traditional implementation
        Calculator calculator = new CalculatorImpl();
        int result = calculator.add(5, 10);
        System.out.println("Sum using traditional method: " + result);
    }
}

// Functional interface with a single abstract method
interface Calculator {
    int add(int a, int b);
}

// Class implementing the interface
class CalculatorImpl implements Calculator {
    @Override
    public int add(int a, int b) {
        return a + b;
    }
}

Explanation:

  • The Calculator interface defines the add method.
  • The CalculatorImpl class provides the implementation.
  • We create an instance of CalculatorImpl and call the add method.

Lambda Expression:


public class LambdaExample {
    public static void main(String[] args) {
        // Using a lambda expression
        Calculator calculator = (a, b) -> a + b;
        int result = calculator.add(5, 10);
        System.out.println("Sum using lambda expression: " + result);
    }
}

interface Calculator {
    int add(int a, int b);
}

Explanation:

  • The Calculator interface remains the same.
  • Instead of implementing the interface in a separate class, we use a lambda expression (a, b) -> a + b to directly provide the implementation.
  • This eliminates the need for the extra class, making the code concise.

Converting Functions to Lambda Expressions

  • To convert a function to a lambda expression, remove the private modifier, return type, and function name, then insert an arrow between parameters and the body .
  • Examples include converting a function that adds two numbers and a function that returns the length of a string into lambda expressions by following the same steps of simplification.

Example: Adding Two Numbers

Using Traditional Method:

public class LambdaExample {
    public static void main(String[] args) {
        MathOperation operation = new MathOperation();
        int sum = operation.add(7, 3);
        System.out.println("Sum using method: " + sum);
    }
}

class MathOperation {
    public int add(int a, int b) {
        return a + b;
    }
}

Explanation:

  • The MathOperation class defines a method add to add two numbers.
  • An object of the MathOperation class is used to call this method.

Using Lambda Expression:

public class LambdaExample {
    public static void main(String[] args) {
        Calculator calculator = (a, b) -> a + b;
        System.out.println("Sum using lambda: " + calculator.add(7, 3));
    }
}

interface Calculator {
    int add(int a, int b);
}

Explanation:

  • The Calculator interface is used directly with a lambda expression (a, b) -> a + b.
  • The lambda provides the implementation in-line, reducing boilerplate code.

Simplifying Lambda Expressions

  • If the body of a lambda expression contains only one statement, curly brackets can be removed for a cleaner look.
  • Type inference allows the compiler to automatically determine the types of parameters, eliminating the need for explicit type declarations.
  • The return keyword can be omitted in lambda expressions, as the compiler understands that a return value is expected.
  • Small brackets can also be removed if there is only one parameter in the lambda expression.

Lambda expressions can be simplified by following these rules

1. Single-Statement Body

If the body contains a single statement, no curly braces are needed.

Calculator calculator = (a, b) -> a + b;

2. Type Inference

The types of parameters can be inferred by the compiler.

 // Without type inference
  Calculator calculator = (int a, int b) -> a + b;
  
  // With type inference
  Calculator calculator = (a, b) -> a + b;

3. Single Parameter Without Parentheses

If there’s only one parameter, parentheses can be omitted.

StringLength stringLength = str -> str.length();

4. Omitting the Return Keyword

For single-expression bodies, the return keyword is implied.

Calculator calculator = (a, b) -> a * b; // Automatically returns the result

Benefits of Using Lambda Expressions

  • Lambda expressions lead to shorter, more readable, and concise code, reducing the size of jar files.
  • They enable parallel processing and facilitate functional programming in Java, enhancing code efficiency and performance.

Example: Iterating Through a List

Without Lambda Expressions:


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

public class LambdaExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
        for (String name : names) {
            System.out.println(name);
        }
    }
}

Explanation: A for loop is used to iterate over the list and print each name.

With Lambda Expressions:


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

public class LambdaExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
        names.forEach(name -> System.out.println(name));
    }
}

Explanation: The forEach method of the List interface takes a lambda expression as an argument. The lambda name -> System.out.println(name) defines the action to be performed for each element.

By replacing traditional implementations with lambda expressions, you can significantly reduce the verbosity of your code while maintaining clarity and functionality.

Explore our more articals

Lambda Expression in Java with Example

Lambda expressions are anonymous functions, meaning they do not have a name, return type, or modifiers. The basic structure of a lambda expression involves removing the modifiers, return type, and method name, and placing an arrow between parameters and the body.

Leave a Comment