A lambda expression is a concise way to represent a function or a block of code that can be passed as an argument, used to implement functional interfaces in Java.
Lambda expressions are a feature introduced in Java 8 that allows us to write code in a concise and functional style. They enable us to represent a method or functionality as an expression without explicitly declaring a method. A lambda expression is an important short block of code that takes in parameters and returns a value.
Suppose you have an e-commerce platform and want to sort a list of products based on their prices. With a lambda expression, you can define the sorting logic in just a single line, saving time and making the code more readable.
Before lambda expressions, writing even small operations required defining an entire class or method, which was tedious and made the code lengthy. Lambda expressions solve this by:
Reducing boilerplate code.
Making code more readable and concise.
Simplifying the use of functional interfaces.
Enabling functional programming in Java.
Now that we understand the benefits of lambda expressions, let’s dive into how they work.
The syntax of lambda expressions is simple and easy to understand:
(parameter_list) -> { body }
parameter_list
: The parameters required for the function. You can omit parentheses if there’s a single parameter.
->
: The arrow operator separates parameters from the function body.
body
: The code to be executed. It can be a single line or multiple lines enclosed in curly braces.
A functional interface is an interface that contains exactly one abstract method. Lambda expressions work with functional interfaces because they implement the single abstract method directly.
Note: A lambda expression in Java must be used with a Functional Interface. It provides an implementation for a Single Abstract Method. Unlike some of the other languages, Java does not allow lambda expressions to be assigned to anything other than a Functional Interface.
Example of functional interface
@FunctionalInterfaceinterface MyFunctionalInterface {void display();}
This example demonstrates a lambda expression that takes no parameters and simply prints a message.
@FunctionalInterfaceinterface Greeting {void sayHello(); // Abstract method that will be implemented using a lambda expression}public class main {public static void main(String[] args) {// Lambda expression implementing the Greeting interfaceGreeting greet = () -> System.out.println("Hello, Educative!");greet.sayHello(); // Calling the lambda expression}}
Explanation: The lambda expression () -> System.out.println("Hello, Educative!")
implements the sayHello
method of the Greeting
interface. Since no parameters are required, the parentheses are empty.
This example shows a lambda expression with one parameter.
@FunctionalInterfaceinterface Printer {void print(String message); // Abstract method with a single parameter}public class main {public static void main(String[] args) {// Lambda expression that accepts one parameter and prints itPrinter printer = message -> System.out.println(message);printer.print("Lambda with one parameter"); // Passing a string to the lambda}}
Explanation: The parameter message
is directly passed to the lambda. Since it's a single parameter, parentheses around it are optional.
This example explains a lambda expression with two parameters and how it calculates the sum.
@FunctionalInterfaceinterface Calculator {int add(int a, int b); // Abstract method with two parameters}public class main {public static void main(String[] args) {// Lambda expression to add two numbersCalculator calc = (a, b) -> a + b;System.out.println("Sum: " + calc.add(5, 10)); // Outputs: Sum: 15}}
Explanation: The parameters (a, b)
are used in the lambda body a + b
to perform addition.
This example demonstrates a lambda that explicitly returns a value.
@FunctionalInterfaceinterface Square {int calculate(int x); // Abstract method with one parameter and a return value}public class main {public static void main(String[] args) {// Lambda expression that returns the square of a numberSquare square = x -> {return x * x;};System.out.println("Square: " + square.calculate(4)); // Outputs: Square: 16}}
Explanation: The lambda x -> {return x * x;};
calculates and returns the square of the input value. Notice the curly braces and the additional semicolon at the end.
forEach
loopThis example shows how lambda expressions simplify iteration over a list.
import java.util.Arrays;import java.util.List;public class main {public static void main(String[] args) {List<String> names = Arrays.asList("Alice", "Bob", "Charlie");// Using a lambda expression to print each namenames.forEach(name -> System.out.println(name));}}
Explanation: The forEach
method accepts a lambda expression, which processes each element of the list. Here, it prints each name.
This example explains how to write multiple lines of code in the lambda body.
@FunctionalInterfaceinterface Logger {void log(String message); // Abstract method with one parameter}public class main {public static void main(String[] args) {// Lambda with multiple statements in the bodyLogger logger = message -> {System.out.println("Logging: " + message);System.out.println("Timestamp: " + System.currentTimeMillis());};logger.log("System started"); // Logs the message with a timestamp}}
Explanation: The curly braces {}
are used to enclose multiple lines in the lambda body.
Modify the Logger
lambda to include the log level (e.g., INFO, ERROR) before the message, and print it in the format: "[LEVEL] Logging: message"
.
Advantages | Disadvantages |
Reduces the need for verbose anonymous classes. | Debugging lambdas can be harder since they lack explicit names. |
Makes code easier to understand for small operations. | Only works with functional interfaces, restricting its application. |
Allows Java to embrace functional programming principles. | Overusing lambdas can make complex code harder to follow. |
Simplifies custom sorting logic for lists or arrays, making the code cleaner and more readable.
Ideal for handling user interface events like button clicks or menu selections with minimal boilerplate.
Efficiently performs filtering, mapping, and other operations on data collections.
Enables concise definitions of tasks for threads or asynchronous programming scenarios.
Which feature of Java allows the use of lambda expressions?
Multithreading
Functional interfaces
Lambda expressions simplify the process of implementing functional interfaces.
They make code more concise and readable for small, single-method operations.
Use cases include sorting, filtering, and iterating over collections.
While lambdas are powerful, they should be used carefully to maintain code readability.
Unlock your Java potential and take control of your coding journey! Start learning Java today to explore more than lambda expression, build Java-based applications, and become a Java developer now!
Haven’t found what you were looking for? Contact Us