Java Lambda Expressions
Pass a small behavior as a value.
Read this topic in தமிழ் ↗.
By the end of this lesson, you can…
- Explain the key idea behind Lambda Expressions.
- Read and run a complete example, then predict what changes.
- Recognize the topic-specific mistake discussed below.
Understand the idea
A lambda supplies an implementation for a functional interface: an interface with one abstract method. It is useful for short callbacks and transformations. A captured local variable must be final or effectively final; keep side effects deliberate.
Explore the details
Java Lambda Expressions
Lambda Expressions were added in Java 8.
A lambda expression is a short block of code that takes in parameters and returns a value. Lambdas look similar to methods, but they do not need a name, and they can be written right inside a method body.
Syntax
The simplest lambda expression contains a single parameter and an expression:
To use more than one parameter, wrap them in parentheses:
Simple expressions must return a value immediately. They cannot contain multiple statements, such as loops or if conditions.
To do more complex work, use a code block with curly braces. If the lambda should return a value, use the return keyword:
Using Lambda Expressions
Lambdas are often passed as arguments to methods. For example, you can use a lambda in the
forEach() method of an ArrayList:
Lambdas in Variables
A lambda expression can be stored in a variable. The variable's type must be an interface with exactly one method (a functional interface). The lambda must match that method's parameters and return type.
Java includes many built-in functional interfaces, such as Consumer (from the java.util package) used with lists.
Lambdas as Method Parameters
You can also pass a lambda expression to a method. The method's parameter must be a functional interface. Calling the interface's method will then run the lambda expression:
Anonymous Class vs. Lambda Expression
Lambdas with the Stream API
Lambdas shine brightest with the Stream API — a powerful way to process collections with a pipeline of operations: filter, transform, and collect in one readable chain.
import java.util.List;
import java.util.stream.Collectors;
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Pipeline: filter evens → square them → collect to list
List<Integer> evenSquares = numbers.stream()
.filter(n -> n % 2 == 0) // keep even numbers
.map(n -> n * n) // square each
.collect(Collectors.toList());
System.out.println(evenSquares); // [4, 16, 36, 64, 100]
// Sum all numbers
int total = numbers.stream()
.reduce(0, Integer::sum);
System.out.println("Sum: " + total); // Sum: 55
// Find any number greater than 7
numbers.stream()
.filter(n -> n > 7)
.findFirst()
.ifPresent(n -> System.out.println("Found: " + n)); // Found: 8Method References
When a lambda just calls an existing method, you can replace it with a method reference using :: — more concise and easier to read.
| Type | Syntax | Lambda equivalent |
|---|---|---|
| Static method | ClassName::methodName | n -> Integer.parseInt(n) → Integer::parseInt |
| Instance method (specific object) | obj::methodName | s -> obj.startsWith(s) → obj::startsWith |
| Instance method (any object) | ClassName::methodName | s -> s.toUpperCase() → String::toUpperCase |
| Constructor | ClassName::new | () -> new StringBuilder() → StringBuilder::new |
In Java 8+, you can often replace an anonymous class with a lambda expression – but only if the interface is a functional interface (one abstract method).
A complete runnable example
This complete Main.java program focuses on the lesson idea. Reference fragments above may demonstrate individual statements; this example includes the imports, entry point, and supporting types it needs.
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
List<Integer> values = Arrays.asList(1, 2, 3);
values.forEach(n -> System.out.println(n * 2));
}
}Predict first. Then reveal the expected output / வெளியீடு
2 4 6
The output shown was checked by running this complete example. Trace the executed statements in order, then compare with your run.
Change it. Run it. Understand it.
Load this lesson example into the editor. Change one value or statement, predict the result, then press RUN to execute Java.
Powered by OneCompiler. Code you run is sent to OneCompiler for execution. For Scanner examples, supply input in the editor I/O panel; for file examples, files exist in its execution environment.
Make it your own
Practice challenge
Change the expression so it prints the square of each value.
Reveal the answer and reasoning / விடை
Use n * n to produce 1, 4, and 9.
One mistake to avoid: A lambda is not automatically asynchronous or parallel. The calling API determines when and how it executes.
Your learning checkpoint
- Explain the example without reading the output first.
- Make the change requested in the practice task.
- Describe why the result changed—or why compilation failed.
Ready to move on? Follow the next lesson in course order, or return to the curriculum to review a prerequisite.