Modern Java 8+ Features ยท Lambdas and Functional Interfaces
Pass behaviour around as a value. Replace a bulky anonymous class with a one-line lambda, and watch it run each time it is used.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class LambdaDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Cara", "Al", "Ben"));
// Before Java 8: an anonymous class just to say "compare by length"
Comparator<String> byLengthOld = new Comparator<String>() {
public int compare(String a, String b) {
return a.length() - b.length();
}
};
// Java 8: the same thing as a lambda
Comparator<String> byLength = (a, b) -> a.length() - b.length();
names.sort(byLength);
Runnable hello = () -> System.out.println("Sorted: " + names);
hello.run();
}
}LambdaDemo$1() has finished, so its variables are gone.byLengthOld.b changes from "Al" to "Cara". In the ArrayList that names points to, index 0 changes from "Cara" to "Al" and index 1 changes from "Al" to "Cara".b changes from "Cara" to "Al".lambda$main$0() has finished, so its variables are gone. In the ArrayList that names points to, index 1 changes from "Cara" to "Ben" and index 2 changes from "Ben" to "Cara".lambda$main$1(), with names = ["Al", "Ben", "Cara"]. It gets its own variables on the stack.lambda$main$1() has finished, so its variables are gone. It prints Sorted: [Al, Ben, Cara].