Same comparator three ways: anonymous, lambda, combinators
Each sort starts from the previous result. The last one sorts by length, then alphabetically when lengths are equal.
Java lets you declare a class inside another class, or even inside a method. A static nested class is an ordinary class that lives in another's namespace; an inner class is tied to one outer object through a hidden reference; local and anonymous classes live inside a block and can read effectively final local variables. Since Java 8, a lambda replaces most anonymous classes that implement a one-method interface.
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 an IntList singly linked list whose Node is a private static nested class. Add add(int) and a toString() that prints [3, 1, 4].
Write Range implements Iterable<Integer> whose iterator is a private inner class reading the outer from and to fields. Loop over new Range(2, 6) with an enhanced for.
Using an anonymous class, create a Supplier<Integer> ticket machine that returns 1, 2, 3 on successive calls. Explain why a plain lambda can't hold that counter itself.
Build three Runnables in a for (int i ...) loop that print task 0, task 1, task 2, plus two more from an enhanced for over List.of("x", "y").
Explain it without notes
What are the four kinds of nested classes, and how do they differ?
Why can an inner class cause a memory leak, and how do you avoid it?
Why must captured local variables be final or effectively final?
How does javac compile nested classes and lambdas? Name the files and synthetic members.
When would you still choose an anonymous class over a lambda?
Expected output
anonymous : [fig, kiwi, apple, banana]
lambda : [kiwi, fig, banana, apple]
comparing : [fig, kiwi, apple, banana]