Lambda Expression in Java 8

This article explores lambda expression in Java, a key feature introduced in Java 8. It explains how Java lambda expressions provide a concise way to implement functional interfaces, enabling functional programming with the Java 8

lambda expression in java

Introduction to Lambda Expressions in java 8

  • 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.

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 (Syntax of 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 in java

  • 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.

Lambda expressions in java can be simplified by following these rules

  • 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.

Simplifying Java Lambda Expressions

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.

Conclusion

in conclusion, the introduction of the lambda expression in Java 8 marked an important change in the java programming language. This feature allows us as to write more concise and readable java code , moving towards a functional style of programming.  Instead of using functional anonymous class declarations, we can now use lambda expression that is introduced by java 8 to implement a functional interface.

 By using a lambda, you focus on what you want to do, rather than how to do it.  Mastering lambda expressions is a key skill for any java programmer looking to write modern java applications.  Whether it’s a simple single expression or a more complex operation, examples of lambda expressions show how they enable functional programming and make java development more efficient.  The use of lambda greatly simplifies the process of working with methods that can be passed around as a value.  An interface in java, especially an interface example with a single abstract method, is the perfect target for a lambda expression was introduced to make code more concise.

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.

2 thoughts on “Lambda Expression in Java (Java 8 Features)”

Leave a Comment