Course contentsShow
← Java
Lesson 657 of 2,87015. Nested and Inner ClassesFree lesson

Practical Migration: Collections and Event Handlers

Real-world examples migrating anonymous Comparators, Runnables, and listeners to lambda expressions.

Practical Migration: Collections and Event Handlers

You'll learn how to convert real-world anonymous classes — Comparators, Runnables, and event listeners — into concise lambda expressions.

The Migration Pattern in Action

Now that you understand lambda conversion rules, let's apply them to code you'll actually write. Three scenarios dominate everyday Java programming: sorting collections, running background tasks, and handling UI events. All involve functional interfaces that were historically implemented with verbose anonymous classes.

Migrating a Comparator

Before (anonymous class):

Collections.sort(names, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        return a.length() - b.length();
    }
});

After (lambda):

Collections.sort(names, (a, b) -> a.length() - b.length());

Migrating a Runnable

Before:

Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Running in background");
    }
});

After:

Thread t = new Thread(() -> System.out.println("Running in background"));

Migrating an Event Listener

Before:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        processClick();
    }
});

After:

button.addActionListener(e -> processClick());

The Common Thread

Notice the pattern: wherever you have a single abstract method (from compare, run, or actionPerformed), the entire anonymous class collapses into just the parameter list and method body. The noise disappears; the intent remains.

Key Takeaway:
When migrating legacy code, replace anonymous implementations of functional interfaces (Comparator, Runnable, ActionListener) with lambda expressions by keeping only parameters and the method body — instantly improving readability and reducing boilerplate.