Java Arena

Module 38

Ordering objects: Comparable and Comparator

Putting objects of your own classes in order. Comparable and compareTo give a class a natural order, which Collections.sort and a stream's sorted() use; a Comparator, written as a lambda or built with Comparator.comparing and reversed, sorts by any other rule; thenComparing sorts by several criteria, in lists and in streams. Last, where an order belongs, in the class or where it's used. MOOC section 10.2.

Steps

  1. Comparable: a natural order for your class
  2. Comparator: an order given to the sort
  3. Several criteria, and sorted streams
  4. Natural order or comparator?