• Articles
  • Tutorials
  • Interview Questions

Lambda Expression in Java

Lambda Expression in Java

This blog will serve as a comprehensive guide to understanding lambda expressions in Java. It covers the syntax, structure, examples, benefits, and recommended practices for effectively utilizing Java lambda expressions.

Table of Content 

Watch this Java video by Intellipaat:

Video Thumbnail

What are Lambda Expressions in Java?

Lambda expressions in Java are anonymous function blocks of code that can be passed around as arguments, stored in variables, or returned from methods without being associated with a specific name. They provide a concise way to represent functionality, enabling a more functional style of programming within Java.

The syntax includes parameters, an arrow token (->), and a body, allowing for a streamlined representation of code blocks. Lambda expressions are primarily used with functional interfaces, making Java code more expressive and concise by reducing repetitive code.

Lambda expressions find extensive use in Java’s Stream API, allowing streamlined operations on collections such as mapping, filtering, and reducing elements. This API, combined with lambda expressions, enables functional-style programming, making code more expressive and allowing for more efficient data processing.

Interested in learning Java? Enroll in our Java online course now!

Basic Syntax and Structure of Lambda Expression in Java

The basic syntax and structure of a lambda expression in Java include:

  • Parameters: These expressions can have no parameters, one parameter, or multiple parameters, all enclosed in brackets. When there’s just one parameter, you can skip the brackets. The types of parameters can be stated directly or figured out by the compiler without stating them explicitly.
    • Example with no parameters: () -> { /* body */ }
    • Example with one parameter: (int x) -> { /* body */ } or simply x -> { /* body */ }
  • Arrow Token (->): The arrow sign marks the division between the parameters and the body of the lambda expression.
  • Body: The body holds the code responsible for executing the task. It can be either a lone statement or a group of statements wrapped within curly braces {}. When it’s a single statement, the braces can be left out.
    Example with a single expression: x -> x * x

Example with a block of code:

// Functional interface
interface MathOperation {
    int operate(int x, int y);
}
public class LambdaExample {
    public static void main(String[] args) {
        // Lambda expression assigned to a functional interface reference
        MathOperation sumOperation = (int x, int y) -> {
            int sum = x + y;
            return sum;
        };
        // Using the lambda expression
        int result = sumOperation.operate(10, 10);
        System.out.println("Sum: " + result);
    }
}

Output

20

Want to learn Java programming, Learn Java from scratch with this free Java Tutorial!

Examples of Lambda Expression in Java

Here are a few examples demonstrating lambda expressions in Java with their respective code and output:

Lambda Expression in Java with No Parameter

A lambda expression in Java without parameters has an empty parameter list () and performs an action without taking any arguments. Here’s an example demonstrating a lambda expression with no parameters:

public class LambdaExample {
    public static void main(String[] args) {
        // Lambda expression with no parameters
        Runnable runnable = () -> {
            System.out.println("Hello, Intellipaat!");
        };
        // Executing the lambda expression
        runnable.run();
    }
}

Output:

Hello, Intellipaat!

Want to ace your next Java interview? Check out our recent blog post about the most common Java interview questions and answers!

Lambda Expression in Java with a Single Parameter

A lambda expression in Java with a single parameter can be defined using the syntax (parameter) -> { /* body */ }. Here’s an example demonstrating a lambda expression with a single parameter:

public class LambdaExample {
    public static void main(String[] args) {
        // Lambda expression with a single parameter
        // Here, the parameter is 'number'
        // The lambda expression squares the given number
        MyInterface square = (number) -> {
            return number * number;
        };
        // Using the lambda expression to square a number
        int result = square.calculate(6); // Square of 6
        System.out.println("Square of 6 is: " + result);
    }
    interface MyInterface {
        int calculate(int number);
    }
}

Output:

Square of 6 is: 36

Get 100% Hike!

Master Most in Demand Skills Now!

Lambda Expression in Java with Multiple Parameters

A lambda expression in Java with multiple parameters is defined using the syntax (parameter1, parameter2, …) -> { /* body */ }. Here’s an example demonstrating a lambda expression with multiple parameters:

public class LambdaExample {
    public static void main(String[] args) {
        // Lambda expression with multiple parameters
        // Here, the parameters are 'a' and 'b'
        // The lambda expression calculates the sum of 'a' and 'b'
        Calculator adder = (a, b) -> {
            return a + b;
        };
        // Using the lambda expression to add two numbers
        int sum = adder.calculate(10, 20); // Sum of 10 and 20
        System.out.println("Sum: " + sum);
    }
    interface Calculator {
        int calculate(int a, int b);
    }
}

Output:

Sum: 30

Lambda Expression in Java with or without Return Keyword

In Java, lambda expressions can be used with or without the explicit return keyword. Here are examples illustrating both scenarios:

Lambda Expression without Using Return Keyword

In Java, lambda expressions allow for concise representations of functional interfaces. When the lambda body consists of a single expression, the return type and the return keyword can be omitted.

public class LambdaExample {
    public static void main(String[] args) {
        // Lambda expression without using the return keyword
        MyInterface adder = (a, b) -> a + b;
        // Using the lambda expression to perform addition
        int sum = adder.calculate(5, 3); // Adding 5 and 3
        System.out.println("Sum: " + sum);
    }
    interface MyInterface {
        int calculate(int a, int b);
    }
}

Output

8

Lambda Expression Using Return Keyword

In Java, lambda expressions can utilize the return keyword when the body of the lambda contains multiple statements or when explicit return handling is needed. 

public class LambdaExample {
    public static void main(String[] args) {
        // Lambda expression using the return keyword
        MyInterface multiplier = (x, y) -> {
            return x * y;
        };
        // Using the lambda expression to perform multiplication
        int product = multiplier.calculate(6, 6); // Multiplying 6 and 6
        System.out.println("Product: " + product);
    }
    interface MyInterface {
        int calculate(int x, int y);
    }
}

Output:

36

Using Lambda Expression with Runnable Interface

Using a lambda expression with the Runnable interface in Java allows for the creation of quick, inline implementations of the run() method, making it easier to work with threads. Here is an example of this:

public class LambdaRunnableExample {
    public static void main(String[] args) {
        // Using lambda expression with Runnable interface
        Runnable runnable = () -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("Count: " + i);
            }
        };
        // Starting a new thread with the lambda expression
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

Output:

Count: 0

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5

Count: 6

Count: 7

Count: 8

Count: 9

Using Lambda Expression with Comparator for Sorting

In Java, the Comparator interface is used to define custom sorting logic for objects. Lambda expressions can be employed to create concise implementations of the compare() method within the Comparator interface, enabling customized sorting behavior without the need for verbose anonymous classes.  Here’s an example of Using Lambda Expression with Comparator for Sorting:

import java.util.*;
public class LambdaComparatorExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
        // Sorting names based on length using lambda expression with Comparator
        Collections.sort(names, (s1, s2) -> Integer.compare(s1.length(), s2.length()));
        // Displaying sorted names
        System.out.println("Sorted Names: " + names);
    }
}

Output:

Sorted Names: [Ram, Ravi, Shyam, GhanShyam]

Learn the basics of Operators in Java through this blog!

Advantages of Lambda Expression in Java

Lambda expressions bring several advantages to Java, enhancing the language’s flexibility and conciseness:

  • Concise Syntax: Lambda expressions offer a more compact way to represent functionality, reducing verbosity in code. They allow the definition of functionality inline, without the need for extensive boilerplate code.
  • Readability: By eliminating unnecessary code, lambda expressions enhance code readability. They make the code more focused on the logic being implemented, improving comprehension, especially for shorter methods or functional interfaces.
  • Improved Collection Libraries: Lambda expressions work seamlessly with Java’s collection libraries and the Stream API, enabling functional-style operations like filtering, mapping, and reducing elements in collections without mutating the original data.
  • Code Flexibility: They offer flexibility in passing behavior as a parameter, allowing methods to accept behaviors (functional interfaces) as arguments, which is beneficial for creating generic methods and APIs.
  • Support for Parallelism: Lambda expressions, especially when used with the Stream API, provide easier parallel processing, enabling efficient utilization of multicore processors.

Crack your next job interview with ease. Find the most commonly asked Java Collection Interview Questions for 2024 here!

Disadvantages of Lambda Expression in Java

While lambda expressions in Java offer several benefits, they also have some limitations and drawbacks:

  • Complexity in Lambdas: Overuse or complex logic within lambda expressions can reduce code readability, making it harder to understand the intent behind the code.
  • Not Suitable for All Scenarios: Lambda expressions are best suited for functional interfaces; however, they might not be ideal for all scenarios or contexts, particularly when dealing with complex control flow or algorithms.
  • Difficulty in Debugging: Debugging lambda expressions might be challenging as they lack explicit names or stack traces, making it harder to pinpoint issues within the lambda body during debugging.
  • Serialization Constraints: Lambda expressions might pose challenges with serialization as they can’t be serialized like regular objects, which can cause issues when working with frameworks or libraries that rely on serialization.
  • Performance Impact: In some cases, using lambda expressions might introduce a slight performance overhead compared to traditional approaches due to the underlying implementation of functional interfaces and object creation.

Best Practices for Using Java Lambda Expressions 

Here are some best practices to consider when using lambda expressions in Java to ensure readability, maintainability, and efficient coding practices:

  • Know What Interfaces You’re Using: Understand the different types of interfaces you can use with lambda expressions in Java. Pick the right one that fits what you need to do.
  • Let Java Guess the Types: Sometimes, you don’t need to tell Java exactly what types you’re using in your lambda expressions. It can figure it out for you. Don’t stress over typing details if you don’t need to.
  • Give Variables Helpful Names: When you use variables inside your lambda expressions, give them names that explain what they’re for. It helps anyone reading your code understand what’s going on.
  • Keep It Simple: Don’t make your lambda expressions too complicated by putting a lot of things inside them. If it starts feeling too tangled, split it into smaller, easier parts.
  • Shortcut with Method References: Sometimes, instead of writing a whole lambda expression, you can refer directly to a method. It makes your code shorter and easier to read, especially for simple things.

Preparing for job interviews? Have a look at our blog on Java 8 Interview Questions!

Conclusion

As Java continues to evolve, lambda expressions are expected to remain a fundamental feature, contributing to the language’s growth and adaptability. Their ability to simplify code, enable functional programming styles, and enhance performance will likely make them an essential part of Java development for years to come.

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Development