Sub topic 1
Why Lambdas? Passing Behavior with Anonymous Classes
Sometimes a method needs more than data from you. It also needs to know how to do part of its job. A sort method needs to know how to compare two items. A thread needs to know what work to run. This chapter shows how Java programmers handed over that kind of "how" before Java 8, why it was clumsy, and how lambdas fix it.
The Problem: A Method That Needs Instructions
Say you have a list of names and you want them sorted. Java can sort strings already, but its default order may not be the one you want.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class DefaultSort {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("Charlie", "alice", "Bob"));
Collections.sort(names);
System.out.println(names); // [Bob, Charlie, alice]
}
}The name alice ends up last. Java's default string order is based on character codes, and every capital letter comes before every lowercase letter. You want alice first because "a" comes before "b" if you ignore case.
The sort method cannot guess this. You have to tell it how to compare two names. In other words, you have to pass it behavior: a small piece of logic, not just a value like a number or a string.
How Java Passes Behavior: Objects That Implement an Interface
Before Java 8, a method could only accept values and objects, so behavior had to be wrapped inside an object.
An interface is a type that lists methods a class promises to provide. Java has an interface called Comparator<T> for exactly this job. Its main method is:
int compare(T a, T b);The method returns a negative number if a should come first, zero if the two are equal, and a positive number if b should come first.
The sort method on a List accepts a Comparator. When sorting, it calls compare again and again on pairs of items. Your object carries the comparing logic, and the sort method runs it.
Option 1: A Named Class
The most direct way is to write a whole class that implements Comparator.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
class IgnoreCaseComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
return a.compareToIgnoreCase(b);
}
}
public class NamedClassSort {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("Charlie", "alice", "Bob"));
names.sort(new IgnoreCaseComparator());
System.out.println(names); // [alice, Bob, Charlie]
}
}This works. But you had to invent a class name, write the class somewhere away from where you use it, and create an object of it. That is a lot of work for one line of real logic: a.compareToIgnoreCase(b).
Option 2: An Anonymous Inner Class
Java has a shortcut. An anonymous inner class is a class with no name that you define and create in one step, right where you need it. You write new, then the interface name, then the class body in braces.
Here is the same sort using an anonymous class, followed by the lambda version that Java 8 added:
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]
}
}The anonymous class keeps the logic next to the call that uses it, which is better than a named class far away. But look at how much code surrounds that one useful line.
Signal vs. Noise
Take the anonymous class apart piece by piece. Most of it is there only because the Java language requires it. Very little of it describes what you actually want.
| Piece of code | Why it is there | Does it tell you something new? |
|---|---|---|
| `new Comparator<String>()` | Names the interface being implemented | Mostly no. `sort` already expects a `Comparator<String>` |
| `@Override` | Marks that a method from the interface is implemented | No |
| `public int compare` | Repeats the method name and return type from the interface | No |
| `(String a, String b)` | Declares the two inputs | Partly. The names matter, but the types are already known |
| `return a.compareToIgnoreCase(b);` | The actual comparing logic | Yes. This is the point |
| Braces and closing `});` | Syntax | No |
The useful part, two inputs and what to do with them, takes about one line. The anonymous class takes six. The lambda (a, b) -> a.compareToIgnoreCase(b) keeps only the inputs and the logic.
This extra code that the language demands but the reader does not need is called boilerplate. Boilerplate makes code longer, harder to scan, and easier to get wrong, for example by forgetting a closing brace.
All three paths give the sort method the same thing: an object it can call compare on. The difference is how much you have to type and read to get there.
The Same Pattern Shows Up Everywhere
Sorting is only one example. Many Java APIs ask you for an object with a single method to run:
Runnablehas one method,run(). Threads use it to know what work to do.Comparatorhascompare(a, b)for ordering.- Event listeners in user interface libraries, such as a button's click handler, often have one method like
actionPerformed(event).
Here is a thread written both ways:
public class ThreadExample {
public static void main(String[] args) throws InterruptedException {
// Anonymous inner class
Thread oldStyle = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello from an anonymous class");
}
});
// Lambda
Thread newStyle = new Thread(() -> System.out.println("Hello from a lambda"));
oldStyle.start();
oldStyle.join(); // wait for the thread to finish
newStyle.start();
newStyle.join();
}
}Output:
Hello from an anonymous class
Hello from a lambdaRunnable.run() takes no inputs, so the lambda starts with empty parentheses (). Once again the lambda keeps only the part that matters: what to print.
When code passes behavior around this often, saving five lines each time adds up. Code like this, where you hand small pieces of logic to other methods, is often called a functional style of programming. Java 8 added lambdas so this style would be practical to write.
What a Lambda Really Is (A Preview)
A lambda expression is a short way to write a piece of behavior that you can pass around like a value. In the examples above, the lambda still becomes an object that implements Comparator or Runnable. The sort method and the thread do not know or care whether you wrote a lambda or an anonymous class.
That raises a fair question. How does Java know that (a, b) -> a.compareToIgnoreCase(b) is a Comparator<String>? You never wrote the word Comparator. The answer has to do with interfaces that have exactly one abstract method, called functional interfaces. They are the subject of the next chapter. Later chapters cover lambda syntax in full and how the compiler works out a lambda's type.
Key Ideas from This Chapter
- Some methods need behavior from you, such as how to compare or what to run.
- Before Java 8, behavior had to be wrapped in an object that implements an interface.
- A named class works but separates the logic from where it is used.
- An anonymous inner class keeps the logic in place but adds a lot of boilerplate.
- A lambda keeps only the inputs and the logic, and it still produces an object the receiving method can call.
Exercise
In the anonymous Comparator class from this chapter, which single line holds the actual sorting logic, and roughly how many lines does the whole anonymous class take?
Show answer
The line return a.compareToIgnoreCase(b); holds the logic. The whole anonymous class takes about six lines (from new Comparator<String>() { to });). The lambda (a, b) -> a.compareToIgnoreCase(b) expresses the same logic in one line.
Exercise
Collections.sort on the list ["Charlie", "alice", "Bob"] prints [Bob, Charlie, alice]. Why does "alice" come last?
Show answer
Java's default string order compares character codes, and all uppercase letters have smaller codes than lowercase letters. "B" and "C" are uppercase, so they come before the lowercase "a". Using compareToIgnoreCase removes this effect.
Exercise
Rewrite this anonymous class as a lambda: new Runnable() { @Override public void run() { System.out.println("Done"); } }
Show answer
() -> System.out.println("Done"). Runnable.run() takes no parameters, so the lambda starts with empty parentheses, then the arrow, then the code to run.
Exercise
Give one situation where a lambda cannot replace an anonymous class.
Show answer
When the object must implement more than one abstract method, needs its own fields (state), or must extend a class instead of implementing a single-method interface. A lambda can only stand in for an interface with exactly one abstract method.