Sub topic 10
Sorted Collections: TreeSet, TreeMap and PriorityQueue
This chapter assumes you know Java classes, generics, Comparable, Comparator, and the basic equals and hashCode methods. A sorted collection uses a comparison rule to decide where each element belongs. That rule can come from Comparable or from a Comparator.
How sorted collections use comparisons
TreeSet, TreeMap, and PriorityQueue all use ordering, but they solve different problems:
| Collection | Stores | Main behavior |
|---|---|---|
| `TreeSet<E>` | Values | Keeps unique values in sorted order |
| `TreeMap<K, V>` | Key-value pairs | Keeps keys sorted |
| `PriorityQueue<E>` | Values | Gives quick access to the smallest element |
A sorted collection usually does not call equals to find its position. It calls compareTo or compare. When the result is zero, the collection treats the objects as equivalent for its ordering.
TreeSet: sorted unique values
A TreeSet stores each value once and iterates over values in order. Its constructor can use natural ordering or accept a comparator.
import java.util.PriorityQueue;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
public class SortedCollectionsDemo {
public static void main(String[] args) {
Set<Integer> numbers = new TreeSet<Integer>();
numbers.add(40);
numbers.add(10);
numbers.add(30);
numbers.add(10);
System.out.println(numbers); // [10, 30, 40]
TreeMap<String, Integer> scores = new TreeMap<String, Integer>();
scores.put("Cara", 91);
scores.put("Ana", 85);
scores.put("Bo", 88);
System.out.println(scores); // {Ana=85, Bo=88, Cara=91}
System.out.println(scores.firstKey()); // Ana
PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
queue.add(30);
queue.add(10);
queue.add(20);
System.out.println(queue.peek()); // 10
System.out.println(queue.poll()); // 10
System.out.println(queue.poll()); // 20
}
}TreeSet does not promise that its internal structure looks like a sorted list. It promises sorted iteration and efficient tree-based lookup, insertion, and removal, typically in logarithmic time.
TreeMap: sorted keys
A TreeMap sorts keys, not values. With natural ordering, string keys use alphabetical order and numeric keys use numeric order. To sort keys differently, pass a comparator to the constructor.
TreeMap<String, Integer> byNameDescending =
new TreeMap<String, Integer>(
java.util.Collections.reverseOrder());
byNameDescending.put("Ana", 85);
byNameDescending.put("Bo", 88);
byNameDescending.put("Cara", 91);
System.out.println(byNameDescending);
// {Cara=91, Bo=88, Ana=85}The comparator determines whether a new key matches an existing key. If compare returns zero, put replaces the existing key's value rather than adding another entry.
PriorityQueue: the next item, not full iteration order
A PriorityQueue keeps its highest-priority element at the head. With natural ordering, the smallest element has priority. peek reads the head without removing it, while poll removes and returns it.
Do not use a PriorityQueue iterator when you need sorted output. The iterator does not guarantee sorted order. Repeatedly call poll instead:
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}A comparator can define another priority, such as largest number first or shortest task first.
Consistency with equals
Ideally, compareTo returns zero exactly when equals returns true. If they disagree, sorted collections can appear to lose values.
BigDecimal is a known example. new BigDecimal("1.0") and new BigDecimal("1.00") are unequal with equals, but their compareTo result is zero. A TreeSet<BigDecimal> therefore keeps only one of them, while a HashSet<BigDecimal> can keep both.
Choose a comparator that reflects the identity rules your collection needs. Document intentional differences.
Exercise
What does a PriorityQueue<Integer> return first when it contains 7, 2, and 5, and what method removes that element?
Show answer
It returns 2 first because natural ordering puts the smallest value at the head. The poll method removes and returns it.