Comparator Interface
Learn Comparator Interface (Comparable & Comparator, Collection Framework) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.
What is a Comparator? A Comparator is a small object that says how to order two objects , kept outside the class. Use it when a class has no natural order, when you cannot edit the class, or when you need several different orders (by name, by height, by trek time...). Package java.util . The interface is Comparator<T> . The one abstract method: int compare(T a, T b) (negative: a first, zero: equal, positive: b first). Because there is only one, a Comparator can be written as a lambda . Many ready-made helper methods ( comparing , thenComparing , reversed , naturalOrder , nullsFirst ...) build...