Skip to main content

Lambda Expressions in Java

  • Java 8 brought a game-changing feature to the language known as lambda expressions.

  • Lambda expressions, inspired by functional programming languages, introduce a concise and expressive way to write anonymous functions.

  • Lambda expressions in Java serve as a clear way to represent anonymous functions or methods without the need for explicit class declarations.

  • They are particularly powerful when used in conjunction with functional interfaces – interfaces with a single abstract method – allowing for a more streamlined approach to writing code.

  • Lambda expressions have three main components:

    1. Parameter List: A list of parameters, similar to method parameters.

    2. Arrow Token (->): Separates the parameter list from the body of the lambda expression.

    3. Body: Contains the code to be executed when the lambda expression is invoked.

Syntax of a Lambda Expression

The syntax of a lambda expression can be broken down into several forms:

1. No Parameters:

() -> System.out.println("Hello, World!");

2. One Parameter (No Parentheses Required):

(name) -> System.out.println("Hello, " + name);

3. Multiple Parameters:

(a, b) -> a + b;

4. Body with Multiple Statements (Requires Curly Braces and Return Statement):

(a, b) -> {
int sum = a + b;
return sum;
};

Example 1: A Simple Lambda Expression

// Traditional Java 7 approach
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Hello, World!");
}
};

// Equivalent Lambda expression in Java 8
Runnable lambdaRunnable = () -> System.out.println("Hello, World!");

In this example, the lambda expression (parameters) -> expression replaces the need for an anonymous class implementing the Runnable interface. It expresses the concept of "runnable" in a more concise manner.

Example 2: Using Lambda with Functional Interfaces

@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}

public class LambdaExample {
public static void main(String[] args) {
// Traditional Java 7 approach
Calculator addition = new Calculator() {
@Override
public int calculate(int a, int b) {
return a + b;
}
};

// Equivalent Lambda expression in Java 8
Calculator lambdaAddition = (a, b) -> a + b;

// Output
System.out.println(addition.calculate(5, 3)); // Output: 8
System.out.println(lambdaAddition.calculate(5, 3)); // Output: 8
}
}

Here, the Calculator functional interface is implemented both traditionally and with a lambda expression. The lambda expression (a, b) -> a + b succinctly defines the behavior of the calculate method.

Benefits of Lambda Expressions:

  1. Conciseness: Lambda expressions reduce boilerplate code, making the codebase more concise and readable.

  2. Readability: The streamlined syntax improves code readability, especially when working with functional interfaces.

  3. Functional Programming: They facilitate a functional programming style, which can lead to more flexible and maintainable code.

Practical Example: Sorting a List

Let's look at a practical example where lambda expressions can be very useful. We will sort a list of strings based on their lengths.

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

public class LambdaSortExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Charlie", "Alice", "Bob");

// Traditional way using anonymous class
names.sort(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
});
System.out.println("Sorted by length (traditional): " + names);

// Using lambda expression
names.sort((s1, s2) -> Integer.compare(s1.length(), s2.length()));
System.out.println("Sorted by length (lambda): " + names);
}
}

In this example:

  • We have a list of names.

  • We sort the list by the length of the names using both the traditional way with an anonymous class and the new way with a lambda expression.

Summary

  • Lambda Expressions: Introduced in Java 8, allow you to write concise and functional-style code.

  • Functional Interfaces: Interfaces with a single abstract method that lambda expressions can implement.

  • Syntax: Can vary from no parameters to multiple parameters, with simple to complex bodies.

  • Advantages: More concise, readable, and expressive code, facilitating functional programming in Java.

Understanding and using lambda expressions is crucial for writing modern, clean, and efficient Java code.