Making Your Classes Collection-Ready

Making Your Classes Collection-Ready in Java: Java's collections are built around a handful of interfaces.

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

  1. Subtraction in compareTo: a - b overflows and reverses the result for extreme values.
  2. compareTo inconsistent with equals: TreeSet then drops elements you consider distinct.
  3. A stateful iterator reused twice: iterator() must return a fresh iterator each call.
  4. next() without checking hasNext(): Should throw NoSuchElementException, not return garbage.
  5. Sorting a mutable field used in ordering: Mutate after inserting into a TreeSet and the structure is corrupt.

Best Practices

  • Comparator.comparing over hand-written comparison logic — shorter and overflow-safe.
  • Comparable for the one natural order, Comparator for everything else.
  • Keep fields used in ordering immutable.
  • Return a fresh iterator every time, so nested loops over the same object work.

Practice Exercises

  1. The Version Sort: Implement Comparable on a Version record and sort 1.2.10, 1.10.0, 1.2.2 correctly.
  2. The Three Orders: Write three comparators for one class and sort the same list three ways without modifying the class.
  3. The Custom Iterable: Make a class iterable that yields the Fibonacci numbers below 100, then loop over it with for-each.