Sub topic 1
Why Lambdas? Passing Behavior with Anonymous Classes
Sometimes you want to give a method a piece of behavior, not just data. For example, you might want to tell a sort method how to compare two names. This chapter shows how Java programmers did that before Java 8, and why the old way led to lambda expressions.
Data vs. Behavior
Most method arguments are data, such as a number, a string, or a list. Behavior is a set of steps, like "compare these two strings and ignore uppercase letters."
Java methods can only accept values, so before Java 8 the behavior had to be wrapped inside an object. That object's class implemented an interface. An interface is a type that lists methods a class promises to provide.
The Comparator Interface
List.sort needs to know how to order items. It asks for a Comparator, which is an interface with one method you must write:
compare(a, b)returns a negative number ifacomes first, zero if the two are equal, and a positive number ifbcomes first.
You could write a whole named class that implements Comparator. That is a lot of work for one line of logic, so Java offers a shortcut.
Anonymous Inner Classes
An anonymous inner class is a class with no name that you define and create in one step, right where you need it. Here is the old way, followed by the Java 8 way:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class SortExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("Charlie", "alice", "Bob"));
// Before Java 8: anonymous inner class
names.sort(new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.compareToIgnoreCase(b);
}
});
// Java 8+: the same behavior as a lambda
names.sort((a, b) -> a.compareToIgnoreCase(b));
System.out.println(names); // [alice, Bob, Charlie]
}
}Save this as SortExample.java, then run javac SortExample.java and java SortExample.
Both calls sort the list the same way. Look at how much code each one needs:
| Part | Anonymous class | Lambda |
|---|---|---|
| `new Comparator<String>()` | Required | Not needed |
| `@Override` and method header | Required | Not needed |
| Parameter types | Written out | Figured out by Java |
| `return` and braces | Required | Not needed |
| Lines of code | 6 | 1 |
The only line that matters is a.compareToIgnoreCase(b). In the anonymous class, the rest is boilerplate, meaning code you must type but that adds no meaning.
Why the Boilerplate Hurts
- It hides the idea. The reader has to skip past several lines to find the one that matters.
- It discourages good design. Passing behavior around is useful, but programmers avoided it when every use cost six lines.
- It is easy to get wrong. More lines mean more chances to make a typo in a type or method name.
A lambda expression is a short way to write a piece of behavior that Java can pass where an interface is expected. The arrow -> separates the inputs (a, b) from the work a.compareToIgnoreCase(b).
Key Points
- Before Java 8, passing behavior meant writing an anonymous inner class.
- Anonymous classes bury one line of logic under several lines of setup.
- Lambdas keep the logic and drop the setup.
Exercise
Rewrite this anonymous class as a lambda: names.sort(new Comparator<String>() { @Override public int compare(String a, String b) { return b.compareTo(a); } });
Show answer
names.sort((a, b) -> b.compareTo(a)); This sorts the names in reverse alphabetical order.
Exercise
In the SortExample program, which single line holds the real sorting logic in both versions?
Show answer
The call a.compareToIgnoreCase(b). Everything else in the anonymous class is boilerplate.