In Java we can use a Comparable or Comparator interface to sort a collection. Both interfaces have some differences you should know in order for you to make the right decision.
Comparable Interface
- We can only sort the collection by a single member of an element.
- Comparable affects the current object being sorted.
- Override compareTo() method.
- Available in the java.lang package
- We sort collection by Collection.sort(collection).
Comparator Interface
- We can sort the collection by multiple members of an element.
- Comparable affects the current object being sorted.
- Override compare() method.
- Available in the java.util package
- We sort collection by Collection.sort(collection,Comparator).