Java 8 (LTS) · Topic 2 of 12
Lambda expressions
Definition​
A lambda is a short piece of code you can pass around, written (input) -> result. It replaces a bulky anonymous class when an interface has just one method.
Example code​
Sorting with a lambda instead of an anonymous class
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class Demo {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ravi", "Asha", "Meera", "Jo"));
// the lambda is the "how to compare" code, passed like a value
names.sort((a, b) -> a.length() - b.length());
System.out.println(names);
Runnable greeting = () -> System.out.println("Hello from a lambda");
greeting.run();
Comparator<String> alphabetical = (a, b) -> a.compareTo(b);
names.sort(alphabetical);
System.out.println(names);
}
}
// Output:
// [Jo, Ravi, Asha, Meera]
// Hello from a lambda
// [Asha, Jo, Meera, Ravi]
Finished this page? Track your progress (saved only in your browser).