What are lambda expressions 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.

Why do we need Java lambda expressions?

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.

Syntax of lambda expression

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.

Functional interface

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

@FunctionalInterface
interface MyFunctionalInterface {
void display();
}

Lambda expression examples in Java

Example: No parameter

This example demonstrates a lambda expression that takes no parameters and simply prints a message.

@FunctionalInterface
interface 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 interface
Greeting 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.

Example: Single parameter

This example shows a lambda expression with one parameter.

@FunctionalInterface
interface 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 it
Printer 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.

Example: Multiple parameters

This example explains a lambda expression with two parameters and how it calculates the sum.

@FunctionalInterface
interface 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 numbers
Calculator 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.

Example: With return keyword

This example demonstrates a lambda that explicitly returns a value.

@FunctionalInterface
interface 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 number
Square 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.

Example: forEach loop

This 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 name
names.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.

Example: Multiple statements

This example explains how to write multiple lines of code in the lambda body.

@FunctionalInterface
interface 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 body
Logger 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 and disadvantages of lambda expressions

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.

Common use cases of lambda expressions

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

1

Which feature of Java allows the use of lambda expressions?

A)

Multithreading

B)

Functional interfaces

Question 1 of 30 attempted

Key takeaways

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

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is a lambda expression in Java?

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.


What does -> mean in Java?

The -> (arrow operator) separates the parameter list of a lambda expression from its body, indicating the implementation of a functional interface method.


Why would you use lambda expressions?

Lambda expressions reduce boilerplate code, improve readability, and enable functional programming by making it easier to implement small, single-method functionalities.


What is the difference between a functional interface and a lambda expression?

A functional interface is an interface with one abstract method, while a lambda expression provides a concise implementation of that method.


Free Resources