JavaIntermediate#collections

What is the difference between Comparable and Comparator?

Comparable defines the natural ordering inside a class (compareTo). Comparator is an external strategy implementing compare(). Use Comparator for multiple sort orders without modifying the class.

Example
class Person implements Comparable<Person> {
  int age;
  public int compareTo(Person o) { return this.age - o.age; }
}
Collections.sort(list, Comparator.comparing(Person::getName));

Related Questions

1
JavaAdvanced#jvm

What is reflection in Java?

Open
2
JavaIntermediate#generics

What are Java generics?

Open
3
JavaAdvanced#generics

Difference between '? extends T' and '? super T'?

Open