Sub topic 3
Defining Key Order with Natural Ordering and Comparators
This chapter assumes you know basic maps and sets, Big-O notation, and binary search. An ordered map or sorted set has to answer one question many times: does key a come before, after, or at the same place as key b? This chapter covers the two ways a language lets you answer it.
Natural ordering
Natural ordering is the default order a type defines for itself. Integers sort by numeric value, and strings sort by character code, one position at a time. In Java, a type gets a natural order by implementing Comparable<T> and its compareTo method. In Python, the built-in types already support <. In C++, std::map uses std::less<Key>, which calls operator<.
The comparison returns a negative number, zero, or a positive number in Java. It works like a three-way answer: before, same place, or after.
import java.util.TreeMap;
public class NaturalOrder {
public static void main(String[] args) {
TreeMap<String, Integer> m = new TreeMap<>();
m.put("pear", 3);
m.put("apple", 1);
m.put("fig", 2);
System.out.println(m); // {apple=1, fig=2, pear=3}
}
}Custom order with a comparator
A comparator is a function that compares two keys and replaces the natural order. Use one when the type has no natural order, or when you want a different order, such as descending or case-insensitive.
import java.util.Comparator;
import java.util.TreeMap;
public class CustomOrder {
public static void main(String[] args) {
TreeMap<Integer, String> desc = new TreeMap<>(Comparator.reverseOrder());
desc.put(10, "ten");
desc.put(30, "thirty");
desc.put(20, "twenty");
System.out.println(desc); // {30=thirty, 20=twenty, 10=ten}
System.out.println(desc.firstKey()); // 30
}
}The structure uses the comparator for every operation, so "first" means first under your order. Navigation methods follow the same rule. In a reversed map, floorEntry finds the entry that comes at or before the key in the reversed order.
Ordering by several fields
Composite keys often need a tie-breaker. Chain comparators so the second field is used only when the first is equal.
import java.util.Comparator;
import java.util.TreeSet;
public class Composite {
record Player(String name, int score) {}
public static void main(String[] args) {
Comparator<Player> byScoreThenName =
Comparator.comparingInt(Player::score).reversed()
.thenComparing(Player::name);
TreeSet<Player> board = new TreeSet<>(byScoreThenName);
board.add(new Player("Ana", 90));
board.add(new Player("Ben", 90));
board.add(new Player("Cy", 95));
board.forEach(System.out::println);
}
}Cy comes first because 95 is the highest score. Ana comes before Ben because the two tie on score, so the name decides.
Python and C++
Python's bisect works on a list sorted by the natural order. Since Python 3.10 it accepts a key function, which plays the role of a comparator for the lookup.
from bisect import insort
words = []
for w in ["Pear", "apple", "Fig"]:
insort(words, w, key=str.lower)
print(words) # ['apple', 'Fig', 'Pear']Pass the same key to every bisect call on that list. If you mix keys, the list is no longer sorted under the order the search assumes.
C++ takes the comparator as a template argument, for example std::map<int, std::string, std::greater<int>>. It must be a strict "less than" test, so < is valid and <= is not.
Exercise
A TreeMap<String, Integer> is built with String.CASEINSENSITIVEORDER. You call put("Fig", 1) and then put("fig", 2). What does the map contain, and why?
Show answer
One entry, with the value 2. The comparator returns zero for "Fig" and "fig", so the map treats them as the same key and replaces the value. The key object kept is the original "Fig".
Exercise
Write a Java comparator that sorts strings by length, shortest first, and breaks ties alphabetically.
Show answer
Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder())