Sorting, Comparators, and Iterators
Java separates natural ordering from custom ordering. Comparable<T> defines a type's natural order; Comparator<T> supplies an external ordering strategy.
record Person(String name, int age) {}
List<Person> people = new ArrayList<>();
people.sort(
Comparator.comparingInt(Person::age)
.thenComparing(Person::name)
);
Iterators allow controlled traversal and, where supported, removal. The enhanced for loop uses an iterator for iterable collections.
Comparators should obey their contract; inconsistent ordering can cause unpredictable sorting behavior.
Key Takeaways
- Use
Comparablefor natural order andComparatorfor alternate orders. - Comparator contracts must be consistent.
- Use collection APIs instead of reimplementing common traversal logic.