From anonymous class to lambda
List.sort is stable: Al and Bo have the same length, so they keep their relative order in both sorts.
A lambda expression is a short, nameless function you can store in a variable or pass to a method, like (a, b) -> a + b. It always becomes an object of a functional interface type, and it can read local variables only if they are effectively final.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write static void repeat(int times, Runnable action) and use it to print Hello 1, Hello 2, Hello 3 using a counter held in an int[].
Sort List.of("kiwi", "fig", "banana", "apple") (copied into an ArrayList) by length, and alphabetically for equal lengths, using one lambda comparator. Print the list.
Write static Function<Integer, Integer> adder(int n) that returns a lambda adding n. Create add5 and add10 and print add5.apply(1), add10.apply(1) and add5.apply(add10.apply(0)).
Explain it without notes
What is a lambda expression, and what decides its type?
Why must captured local variables be effectively final, while fields can change?
How does this behave inside a lambda compared with an anonymous class?
How does the JVM create a lambda object at runtime?
Expected output
anonymous class: [Al, Bo, Ravi, Meera]
lambda, reversed: [Meera, Ravi, Al, Bo]
Hello from a lambda
Hello from a lambda