Back to Java
2025-12-235 min read

Java Lambda Expressions

Learn Java Lambda Expressions step by step with clear examples and exercises.

Why This Matters

Lambda expressions are a key feature of the Java 8 release, introducing functional programming concepts to the Java language. This guide will cover the why, what, and how of lambda expressions, providing practical examples, common mistakes, practice questions, and frequently asked questions.

Why Lambda Expressions Matter

Lambda expressions enable more concise and flexible code by allowing the creation of anonymous functions at runtime. They are particularly useful in scenarios where you need to pass a function as an argument to another method or use it in a concurrent context. Understanding lambda expressions is essential for modern Java development, as they are widely used in libraries like Stream API, CompletableFuture, and functional interfaces such as java.util.function.*.

Prerequisites

To fully grasp the concepts presented in this guide, you should have a solid understanding of:

  • Basic Java syntax, including variables, methods, and control structures
  • Object-oriented programming principles in Java
  • Exception handling
  • Concurrency and multi-threading in Java (optional but recommended)

Core Concept

Functional Interfaces

Functional interfaces are single-abstract-method interfaces introduced in Java 8. The most commonly used functional interfaces include:

  1. java.util.function.Function - applies a function to an input and produces a result
  2. java.util.function.Consumer - accepts a single input and returns no result (void)
  3. java.util.function.Supplier - produces a result with no input
  4. java.util.function.Predicate - tests if an input satisfies a certain condition
  5. java.util.function.UnaryOperator - applies a function to a single input and returns the modified input as output
  6. java.util.function.BinaryOperator - applies a binary operator to two inputs and produces a result

Lambda Expressions Syntax

A lambda expression consists of:

  1. Parameter list enclosed in parentheses
  2. Arrow token (->)
  3. Function body

Here's an example of a simple lambda expression implementing the java.util.function.Function interface:

Function<Integer, Integer> square = (num) -> num * num;

In this example, square is the name of the lambda function, which takes an Integer as input and returns the squared value. The parameter list consists of a single integer variable named num, and the function body is the expression num * num.

Lambda Expression with Multiple Statements

If your lambda function requires multiple statements, you can enclose them in curly braces and return the result using the return keyword:

Function<Integer, String> toWord = (num) -> {
if (num < 0) {
return "Negative";
} else if (num == 0) {
return "Zero";
} else {
return "Positive";
}
};

In this example, toWord is a lambda function that takes an integer and returns a string indicating whether the number is negative, zero, or positive.

Worked Example

Let's consider a simple problem: sorting a list of names in alphabetical order using lambda expressions and the Stream API.

import java.util.*;

public class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");
Collections.sort(names, (n1, n2) -> n1.compareToIgnoreCase(n2));
System.out.println(names);
}
}

In this example, we create a list of names and use the Collections.sort() method to sort them in alphabetical order using a custom comparator implemented as a lambda expression. The compareToIgnoreCase() method is used to ensure case-insensitive comparison.

Common Mistakes

  1. Forgetting to import functional interfaces: Make sure you have imported the necessary functional interfaces for your lambda expressions, such as java.util.function.*.
  2. Incorrect parameter types or number of parameters: Ensure that the parameter list in your lambda expression matches the expected type and number of arguments for the functional interface.
  3. Not returning a result from a lambda function: If your lambda function is expected to return a value but does not, you will encounter compilation errors.
  4. Misusing lambda expressions: Lambda expressions should be used judiciously and not as a replacement for traditional methods in every situation.
  5. Confusing functional interfaces with regular interfaces: Functional interfaces have a single abstract method, whereas regular interfaces may contain multiple abstract methods.

Practice Questions

  1. Write a lambda expression that takes two integers and returns their sum.
  2. Implement a lambda function that filters out names containing the letter 'a' from a list of names.
  3. Sort a list of strings in reverse alphabetical order using a lambda expression and the Stream API.
  4. Create a lambda function that applies a discount to a product price based on the quantity purchased (e.g., 10% off for quantities greater than 5).

FAQ

Q: Can I use lambda expressions with older versions of Java?

A: Lambda expressions were introduced in Java 8, so they are not available in earlier versions. However, you can use libraries like Guava to achieve similar functionality.

Q: How does the JVM handle lambda expressions at runtime?

A: The JVM creates a class for each lambda expression and assigns it an implementation of the corresponding functional interface. This allows lambda expressions to be used seamlessly within existing Java code.

Q: What is the difference between a method reference and a lambda expression?

A: A method reference is a shorthand way to create a lambda expression that refers to an existing method in another class. It provides a more concise syntax for certain use cases, such as sorting arrays or filtering collections.

Q: Are lambda expressions thread-safe?

A: Lambda expressions are not inherently thread-safe and should be used carefully within concurrent contexts. If you need to ensure thread safety, consider using java.util.concurrent.locks.* classes for synchronization or use libraries like Project Reactor or Akka for more advanced concurrency management.

Java Lambda Expressions | Java | XQA Learn