Java Lambda Expressions
In this page:
(parameters) -> expression
(parameters) -> {
// statements
return value;
}
What is a Lambda Expression?
Lambda expressions are anonymous, unnamed functions that simplify your code by eliminating the boilerplate of writing a full class just to pass around a single behavior. They let you treat a piece of functionality as a method argument, essentially treating code itself as data you can pass around.
Example: What is a Lambda Expression?
// Define the class Main
public class Main {
// Define the interface Greeting
interface Greeting {
void greet();
}
// Program entry point: the JVM starts running here
public static void main(String[] args) {
Greeting g = () -> System.out.println("Hello from a lambda");
g.greet();
}
}
Login to try C/C++/Java/PHP code in the editor
Lambda with Parameters
You can pass parameters to a lambda expression by declaring them inside the parentheses on the left side of the arrow (->) operator, just like a normal method's parameter list, except Java can usually infer their types automatically.
Example: Lambda with Parameters
// Define the class Main
public class Main {
// Define the interface Adder
interface Adder {
int add(int a, int b);
}
// Program entry point: the JVM starts running here
public static void main(String[] args) {
Adder adder = (a, b) -> a + b;
// Print a line to the console
System.out.println(adder.add(3, 4));
}
}
Login to try C/C++/Java/PHP code in the editor
Lambda with Return Values
If a lambda body contains only a single expression, Java automatically returns its value without requiring an explicit return keyword, keeping one-liners compact. For multi-statement bodies, wrap the code in curly braces and write an explicit return statement, just like an ordinary method.
Example: Lambda with Return Values
public class Main {
interface Square {
int of(int n);
}
public static void main(String[] args) {
Square oneLiner = n -> n * n; // implicit return
Square multiLine = n -> {
int result = n * n;
return result;
};
System.out.println(oneLiner.of(4) + " " + multiLine.of(5));
}
}
Login to try C/C++/Java/PHP code in the editor
Lambdas and Variable Scope
Lambda expressions can freely read instance or static variables from their enclosing scope, but they can only capture local variables that are declared final or are effectively final, meaning never reassigned after initialization. This restriction exists because the lambda may run later, on a different thread, after the original local variable would otherwise have gone out of scope.
Example: Lambdas and Variable Scope
public class Main {
interface Printer {
void print();
}
public static void main(String[] args) {
final int count = 10; // effectively final, safe to capture
Printer p = () -> System.out.println("Count is " + count);
p.print();
}
}
Login to try C/C++/Java/PHP code in the editor
Common Use Cases
Lambda expressions are most commonly used to write concise collection iteration, filtering predicates, or custom sorting comparators inline, right where they're needed, instead of as separate named classes scattered elsewhere in the codebase.
Example: Common Use Cases
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(5, 3, 8, 1));
nums.removeIf(n -> n < 4); // filtering predicate
nums.sort((a, b) -> b - a); // custom comparator
System.out.println(nums);
}
}
Login to try C/C++/Java/PHP code in the editor
- Modifying a local variable from inside a lambda, like
count++, which does not compile because captured locals must be final or effectively final. - Using a lambda where the target type is not a functional interface, such as
var f = () -> 5;or an interface with two abstract methods. - Thinking
thisinside a lambda refers to the lambda, when it refers to the enclosing class instance.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: