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
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.
How It Works
Here is a step-by-step walkthrough of how the Java program for Lambda Expression Example in Java runs, line by line:
interface MathOperation {— performs part of the program’s logic.int operate(int a, int b);— declares or assigns a value the program uses.public class LambdaDemo {— performs part of the program’s logic.public static void main(String[] args) {— defines a function used by the program.Runnable task = () -> System.out.println("Running in a lambda");— writes a line of output shown in the sample output.task.run();— performs part of the program’s logic.List<String> names = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));— declares or assigns a value the program uses.names.sort((a, b) -> a.compareToIgnoreCase(b));— performs part of the program’s logic.
After running it, compare your console output with the Sample Output above. Try changing the values and re-running the program to see how the result changes — experimenting is the fastest way to understand the logic.
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.