-> (lambda)
A lambda expression — a short function that can be passed around as a value.
Available since: Java 8
Syntax
(parameters) -> expression
(parameters) -> { statements; }Examples
The forms of syntax:
void main() {
Runnable hello = () -> IO.println("Hello");
Function<Integer, Integer> square = x -> x * x;
BinaryOperator<Integer> add = (a, b) -> a + b;
Function<String, String> shout = s -> {
String upper = s.toUpperCase();
return upper + "!";
};
hello.run();
IO.println(square.apply(5));
IO.println(add.apply(2, 3));
IO.println(shout.apply("hi"));
}Output:
Hello
25
5
HI!A lambda as a method argument:
void main() {
List<String> names = new ArrayList<>(List.of("Oleg", "Anna", "Ivan"));
names.sort((a, b) -> a.compareTo(b));
names.forEach(n -> IO.println("- " + n));
}Output:
- Anna
- Ivan
- OlegNotes
A lambda always implements a functional interface — an interface with a single abstract method (Function, Predicate, Runnable, Comparator). Parentheses around a single parameter and braces around a single expression can be omitted. Outer local variables are read-only inside a lambda: they must be effectively final.
See also
- :: (method reference) — A method reference — an even shorter replacement for a lambda that only calls a method.
- Function — A function that takes a value of type `T` and returns a value of type `R`.
- Predicate — A condition: a function that takes a value and returns a `boolean`.
- Consumer — An action that takes a value and returns nothing.
In the tutorial
- Lambda expressions — Lambdas in Java: writing a function as a value, syntax forms, passing lambdas to methods and capturing variables.