Introduction
Java Lambda Expressions were introduced in Java 8 as one of the most significant enhancements to the Java programming language. Lambda expressions allow developers to write concise, readable, and functional-style code by eliminating unnecessary boilerplate code, especially when working with functional interfaces, collections, and the Stream API.
Before Java 8, developers had to create anonymous inner classes to implement interfaces with a single abstract method. This approach required writing a lot of repetitive code. Lambda expressions simplify this by allowing you to implement the method directly using a short and expressive syntax.
For example, instead of writing:
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello Java");
}
};
You can simply write:
Runnable r = () -> System.out.println("Hello Java");
This reduces code size, improves readability, and makes Java programming more modern and expressive.
Lambda expressions are widely used with the Collections Framework, Streams, Comparator, Thread creation, Event handling, and Functional Interfaces such as Predicate, Consumer, Supplier, and Function.
In this tutorial, you’ll learn everything about Java Lambda Expressions, including syntax, features, functional interfaces, examples, real-life applications, advantages, limitations, common mistakes, best practices, and interview questions.
What are Java Lambda Expressions?
A Lambda Expression is an anonymous function that can be passed as an argument or assigned to a variable.
A lambda expression has:
- No method name
- No access modifier
- No return type declaration
- A parameter list
- A body
It provides the implementation of a method defined in a Functional Interface.
Example:
(int a, int b) -> a + b
This lambda expression accepts two integers and returns their sum.
Why Do We Need Lambda Expressions?
Before Java 8, implementing a functional interface required an anonymous inner class.
Example:
interface Greeting {
void sayHello();
}
Without Lambda:
Greeting g = new Greeting() {
@Override
public void sayHello() {
System.out.println("Hello");
}
};
With Lambda:
Greeting g = () -> System.out.println("Hello");
The lambda version is shorter, cleaner, and easier to understand.
Features of Lambda Expressions
Some important features are:
- Introduced in Java 8
- Reduces boilerplate code
- Improves readability
- Supports functional programming
- Works with Functional Interfaces
- Enables parallel processing with Streams
- Can be passed as method arguments
- Supports closures
- Improves maintainability
- Integrates with the Stream API
Syntax
General syntax:
General syntax:
(parameters) -> expression
or
(parameters) -> {
// statements
}
Examples:
No parameter
() -> System.out.println("Hello");
One parameter
name -> System.out.println(name);
Two parameters
(a, b) -> a + b;
Multiple statements
(a, b) -> {
int sum = a + b;
return sum;
}
Understanding the Parts of a Lambda Expression
Example:
(int x, int y) -> x + y
Components:
- (int x, int y) → Parameters
- -> → Lambda operator
- x + y → Expression body
Functional Interface
A Lambda Expression works only with a Functional Interface.
A Functional Interface contains exactly one abstract method.
Example:
@FunctionalInterface
interface Calculator {
int add(int a, int b);
}
Lambda implementation:
Calculator c = (a, b) -> a + b;
Example 1: Lambda Without Parameters
interface Greeting {
void hello();
}
public class Main {
public static void main(String[] args) {
Greeting g =
() -> System.out.println("Welcome to Java");
g.hello();
}
}
Output
Example 2: Lambda with One Parameter
interface Message {
void print(String name);
}
public class Main {
public static void main(String[] args) {
Message m =
name -> System.out.println("Hello " + name);
m.print("Rahul");
}
}
Output
Example 3: Lambda with Multiple Parameters
interface Addition {
int add(int a, int b);
}
public class Main {
public static void main(String[] args) {
Addition ad =
(a, b) -> a + b;
System.out.println(ad.add(10, 20));
}
}
Output
Example 4: Lambda with Multiple Statements
interface Multiply {
int multiply(int a, int b);
}
public class Main {
public static void main(String[] args) {
Multiply m = (a, b) -> {
int result = a * b;
return result;
};
System.out.println(m.multiply(5, 6));
}
}
Output
Example 5: Sorting Using Lambda
Before Java 8:
Collections.sort(list, new Comparator() {
@Override
public int compare(String a,
String b) {
return a.compareTo(b);
}
});
Using Lambda:
Collections.sort(list,
(a, b) -> a.compareTo(b));
This is shorter and more readable.
Example 6: Lambda with forEach()
import java.util.*;
public class Main {
public static void main(String[] args) {
List names =
Arrays.asList("Rahul",
"Amit",
"Neha");
names.forEach(name ->
System.out.println(name));
}
}
Output
Amit
Neha
Example 7: Lambda with Thread
public class Main {
public static void main(String[] args) {
Thread t =
new Thread(() ->
System.out.println("Thread Running"));
t.start();
}
}
Output
Lambda Expressions with Stream API
One of the biggest advantages of Lambda Expressions is their integration with the Stream API.
Example:
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10,20,30,40,50);
numbers.stream()
.filter(n -> n > 20)
.forEach(System.out::println);
}
}
Output
40
50
Built-in Functional Interfaces
Java provides several predefined functional interfaces.
| Interface | Method | Purpose |
|---|---|---|
| Predicate | test() | Returns true or false |
| Function | apply() | Converts one value to another |
| Consumer | accept() | Consumes a value |
| Supplier | get() | Supplies a value |
| UnaryOperator | apply() | Operates on one operand |
| BinaryOperator | apply() | Operates on two operands |
Example:
Predicate<Integer> even =
n -> n % 2 == 0;
System.out.println(even.test(10));
Output
Lambda vs Anonymous Inner Class
| Feature | Lambda | Anonymous Class |
|---|---|---|
| Code Size | Short | Long |
| Readability | High | Moderate |
| Performance | Better | Slightly Lower |
| Boilerplate Code | Very Less | More |
| Requires Class | No | Yes |
| Java Version | Java 8+ | All Versions |
Imagine an E-commerce Application where products need to be sorted by price.
Traditional approach:
Collections.sort(products,
new PriceComparator());
Using Lambda:
Collections.sort(products,
(p1, p2) ->
Double.compare(p1.getPrice(),
p2.getPrice()));
Other real-world applications include:
- Employee management systems
- Banking software
- Student management systems
- Event handling in GUI applications
- Data filtering
- Report generation
- Multi-threaded programming
- Stream processing
Advantages of Lambda Expressions
- Less boilerplate code
- Improved readability
- Supports functional programming
- Better integration with Streams
- Easy event handling
- Simplifies Comparator implementation
- Improves maintainability
- Encourages clean coding practices
Limitations of Lambda Expressions
- Can only implement Functional Interfaces
- Not suitable for complex business logic
- Debugging may be more difficult than traditional methods
- Excessive use may reduce readability if expressions become too complex
Common Mistakes
1. Using Lambda with Non-Functional Interfaces
Incorrect:
interface Demo {
void method1();
void method2();
}
A lambda expression cannot implement this interface because it has more than one abstract method.
2. Forgetting Parentheses for Multiple Parameters
Incorrect:
a, b -> a + b
Correct:
(a, b) -> a + b
3. Forgetting the return Statement in a Block Lambda
Incorrect:
(a, b) -> {
a + b;
}
Correct:
(a, b) -> {
return a + b;
}
4. Writing Unnecessarily Long Lambda Expressions
Avoid putting complex business logic inside a lambda. Instead, move the logic to a separate method and call it from the lambda.
5. Ignoring Method References
Instead of:
list.forEach(name -> System.out.println(name));
Use:
list.forEach(System.out::println);
Method references improve readability.
Best Practices
- Use Lambda Expressions only with Functional Interfaces.
- Keep lambda expressions short and readable.
- Prefer method references when they make the code simpler.
- Use built-in functional interfaces such as Predicate, Function, Consumer, and Supplier.
- Combine Lambda Expressions with the Stream API for data processing.
- Avoid placing complex business logic directly inside lambda expressions.
Time Complexity
A lambda expression itself does not determine time complexity. The complexity depends on the operation being performed
| Operation | Time Complexity |
|---|---|
| Lambda Invocation | O(1) |
| Collections.sort() with Lambda | O(log n) |
| Stream filter() | O(n) |
| Stream map() | O(n) |
| Stream forEach() | O(n) |
Conclusion
Java Lambda Expressions have transformed the way developers write Java code by introducing a concise and expressive syntax for implementing Functional Interfaces. They reduce boilerplate code, improve readability, and integrate seamlessly with modern Java features such as the Stream API, Collections Framework, and built-in functional interfaces.
Whether you’re sorting collections, processing streams, creating threads, or implementing callbacks, Lambda Expressions help you write cleaner and more maintainable code. By understanding their syntax, features, best practices, and common pitfalls, you’ll be well-equipped to build modern Java applications and confidently answer Java 8 interview questions.