Lambda Expression Example in Java
On this page (8sections)
Introduction
Lambda expressions (Java 8+) provide a concise way to pass behaviour as data. They are widely used with collections, streams and event handlers.
Syntax
(parameters) -> expression
(parameters) -> { statements; }
Example Program
import java.util.*;
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
public class LambdaDemo {
public static void main(String[] args) {
// Runnable lambda
Runnable task = () -> System.out.println("Running in a lambda");
task.run();
// Comparator lambda
List<String> names = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));
names.sort((a, b) -> a.compareToIgnoreCase(b));
System.out.println("Sorted: " + names);
// Custom functional interface
MathOperation add = (x, y) -> x + y;
MathOperation multiply = (x, y) -> x * y;
System.out.println("Add : " + add.operate(6, 7));
System.out.println("Multiply : " + multiply.operate(6, 7));
}
}
Sample Output
Running in a lambda
Sorted: [Alice, Bob, Charlie]
Add : 13
Multiply : 42
How It Works
() -> ...implements the single abstract method ofRunnable.(a, b) -> a.compareToIgnoreCase(b)implementsComparator.compare.- Custom functional interfaces define the contract; the lambda supplies the implementation body.
Best Practices
- Keep lambdas short; extract complex logic into named methods.
- Prefer method references (
String::compareToIgnoreCase) when they improve readability. - Annotate custom single-method interfaces with
@FunctionalInterface.
Common Mistakes
- Using lambdas where the target type is ambiguous (compiler cannot infer the functional interface).
- Modifying non-final outer variables from inside a lambda.
Frequently Asked Questions
What is a functional interface?
A functional interface has exactly one abstract method. Lambda expressions can replace anonymous inner classes that implement such interfaces. Examples include Runnable, Comparator and custom interfaces annotated with @FunctionalInterface.
Can lambdas access local variables?
Yes, but only final or effectively final local variables from the enclosing scope.