Sub topic 2
Comparator: Ordering from Outside the Class
Assume you know Java classes, generics, lists, lambdas, method references, and basic collections. A Comparator<T> is an object that defines how to compare two values of type T. It keeps an ordering separate from the class being ordered.
This is useful when a class needs several orderings. For example, Person might be ordered by age in one screen and by name in another.
Writing Comparators with Lambdas and Method References
The compare method returns:
- A negative number when the first value comes before the second.
- Zero when the values are equal for this ordering.
- A positive number when the first value comes after the second.
import java.util.Arrays;
import java.util.Comparator;
class Person {
final String name;
final int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
String getName() {
return name;
}
int getAge() {
return age;
}
public String toString() {
return name + ":" + age;
}
}
public class Main {
public static void main(String[] args) {
Person[] people = {
new Person("Ana", 31),
new Person("Bo", 25),
new Person("Cy", 31)
};
Comparator<Person> byAge = (a, b) -> Integer.compare(a.age, b.age);
Comparator<Person> byName = Comparator.comparing(Person::getName);
Arrays.sort(people, byAge);
System.out.println(Arrays.toString(people));
Arrays.sort(people, byName);
System.out.println(Arrays.toString(people));
}
}A lambda gives the comparison logic directly. A method reference passes an existing getter to a comparator factory.
Building Comparator Chains
Factory methods make multi-key ordering readable. thenComparing compares a second property only when the first property ties. reversed changes the direction of the comparator it follows.
Comparator<Person> oldestFirstThenName =
Comparator.comparingInt(Person::getAge)
.reversed()
.thenComparing(Person::getName);Sorting Lists, Arrays, and Streams
Use list.sort(comparator) for a mutable list, Arrays.sort(array, comparator) for an object array, and stream.sorted(comparator) when producing sorted results without changing the source.
Exercise
Which comparator sorts people by age, from youngest to oldest?
Show answer
Comparator.comparingInt(Person::getAge).