Card 03/ 09
Comparator Example: One Invoice Type Sorted Three Ways
Three screens want three orders, and not a line is added to the Invoice class.
A Comparator supplies an order from outside the class, at the place where sorting happens, so one type can be sorted differently for different callers. The finance screen wants the largest amounts first, the chase list the oldest due date, and the audit export reference order:
invoices.sort(Comparator.comparingLong(Invoice::pence).reversed());
chasing.sort(Comparator.comparing(Invoice::due));
export.sort(Comparator.comparing(Invoice::reference));Three orders, three call sites, and nothing added to Invoice. Each Comparator answers the same two-argument question, built where the order is wanted rather than where the type is declared, and then discarded once the sort has finished.
Put this beside an Invoice that implements Comparable to sort itself by due date, and the shared structure comes out: in both cases something implemented a two-argument comparison, and the only difference is who owns it. Comparable makes the answer part of the type, for everyone. Comparator makes it an argument, decided per call.
← → move through sections and cards