Concept Explanation
Java's collections are built around a handful of interfaces. Implement them on your own types and your classes work with sort, for-each, TreeSet, and streams for free.
Comparable: Natural Order
Comparable defines the one obvious way to order your type:
public class Version implements Comparable<Version> {
private final int major, minor, patch;
@Override
public int compareTo(Version other) {
return Comparator.comparingInt((Version v) -> v.major)
.thenComparingInt(v -> v.minor)
.thenComparingInt(v -> v.patch)
.compare(this, other);
}
}
Collections.sort(versions); // just works
new TreeSet<>(versions); // sorted automatically
versions.stream().max(Comparator.naturalOrder());
The contract: return negative if this comes first, zero if equal, positive if later. Never implement it with subtraction (this.value - other.value) — that overflows for large or negative ints. Use Integer.compare.
Consistency matters: if compareTo returns 0, equals should return true. TreeSet uses compareTo to decide uniqueness, so an inconsistent pair means "duplicates" silently disappear.
Comparator: Alternative Orders
Comparable gives one order. Comparator gives as many as you need:
Comparator<Employee> bySalary = Comparator.comparing(Employee::getSalary);
Comparator<Employee> byName = Comparator.comparing(Employee::getName);
Comparator<Employee> combined =
Comparator.comparing(Employee::getDepartment)
.thenComparing(Employee::getSalary, Comparator.reverseOrder())
.thenComparing(Employee::getName);
employees.sort(combined);
Null-safe when data is imperfect:
Comparator.comparing(Employee::getNickname,
Comparator.nullsLast(Comparator.naturalOrder()));
Iterable: Supporting for-each
Implement Iterable and your type works in an enhanced for loop:
public class Playlist implements Iterable<Song> {
private final List<Song> songs = new ArrayList<>();
@Override
public Iterator<Song> iterator() {
return songs.iterator(); // delegate to the backing list
}
}
for (Song s : playlist) { // legal now
System.out.println(s.title());
}
A hand-written iterator when there is no backing collection:
public class Countdown implements Iterable<Integer> {
private final int from;
public Countdown(int from) { this.from = from; }
@Override
public Iterator<Integer> iterator() {
return new Iterator<>() {
private int current = from;
public boolean hasNext() { return current > 0; }
public Integer next() { return current--; }
};
}
}
Records Do Most of This
public record Point(int x, int y) implements Comparable<Point> {
@Override
public int compareTo(Point o) {
return Comparator.comparingInt(Point::x)
.thenComparingInt(Point::y)
.compare(this, o);
}
}
equals, hashCode, toString, and accessors are generated — you write only the ordering.
Common Mistakes
- Subtraction in
compareTo:a - boverflows and reverses the result for extreme values. compareToinconsistent withequals:TreeSetthen drops elements you consider distinct.- A stateful iterator reused twice:
iterator()must return a fresh iterator each call. next()without checkinghasNext(): Should throwNoSuchElementException, not return garbage.- Sorting a mutable field used in ordering: Mutate after inserting into a
TreeSetand the structure is corrupt.
Best Practices
Comparator.comparingover hand-written comparison logic — shorter and overflow-safe.Comparablefor the one natural order,Comparatorfor everything else.- Keep fields used in ordering immutable.
- Return a fresh iterator every time, so nested loops over the same object work.
Practice Exercises
- The Version Sort: Implement
Comparableon aVersionrecord and sort1.2.10,1.10.0,1.2.2correctly. - The Three Orders: Write three comparators for one class and sort the same list three ways without modifying the class.
- The Custom Iterable: Make a class iterable that yields the Fibonacci numbers below 100, then loop over it with for-each.