Sub topic 10
Sorted Collections: TreeSet, TreeMap and PriorityQueue
This chapter assumes you can write a Comparator with the factory methods, you know the compare contract (sign of the result, consistency, transitivity), and you know how equals and hashCode drive HashSet and HashMap. Here you will see how TreeSet, TreeMap and PriorityQueue use ordering, and which mistakes make them misbehave.
Ordering is the whole definition of the collection
HashSet and HashMap ask "are these two elements equals?". TreeSet and TreeMap never call equals. They ask only "does compare (or compareTo) return 0?". The ordering decides where an element goes, whether it is a duplicate, and whether a lookup finds it.
You choose the ordering when you construct the collection:
- With no argument, the collection uses the elements' natural ordering and casts them to
Comparable. - With a
Comparatorargument, the collection uses that comparator and ignores any natural ordering.
TreeSet
A TreeSet is a sorted set backed by a red-black tree. add, remove and contains take O(log n). Iteration returns elements in sorted order.
import java.util.Set;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
Set<String> names = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
names.add("Ana");
names.add("bo");
names.add("ANA"); // compare returns 0 against "Ana", so it is ignored
names.add("Cy");
System.out.println(names); // [Ana, bo, Cy]
System.out.println(names.contains("BO")); // true
}
}"ANA" is rejected even though "ANA".equals("Ana") is false. contains("BO") succeeds for the same reason. The comparator is the only notion of equality the set has.
Because the set is ordered, it also offers navigation methods that HashSet cannot:
first()andlast()floor(x)andlower(x): the greatest element at mostx, or strictly less thanxceiling(x)andhigher(x): the least element at leastx, or strictly greater thanxheadSet,tailSetandsubSet: live views of a rangedescendingSet(): a live view in reverse order
TreeMap
TreeMap applies the same rules to its keys. The values are never compared. Its navigation methods come in key and entry forms, such as floorKey and floorEntry.
import java.util.TreeMap;
public class GradeDemo {
public static void main(String[] args) {
TreeMap<Integer, String> grades = new TreeMap<>();
grades.put(0, "F");
grades.put(60, "D");
grades.put(70, "C");
grades.put(80, "B");
grades.put(90, "A");
int score = 84;
System.out.println(grades.floorEntry(score).getValue()); // B
System.out.println(grades.headMap(70)); // {0=F, 60=D}
System.out.println(grades.tailMap(80, true)); // {80=B, 90=A}
System.out.println(grades.descendingMap()); // {90=A, 80=B, 70=C, 60=D, 0=F}
}
}floorEntry is the idiomatic way to do range lookups such as grade bands, tax brackets or time-based schedules. A HashMap cannot answer "which key is closest below this one?".
The range views (headMap, tailMap, subMap) are windows onto the original map, not copies. Writing through a view changes the underlying map. Inserting a key outside the view's range throws IllegalArgumentException.
PriorityQueue
A PriorityQueue is a binary heap. Unlike the tree classes, it keeps only one guarantee: the head of the queue (peek, poll) is the least element according to the ordering. The rest is partially ordered.
import java.util.Comparator;
import java.util.PriorityQueue;
public class QueueDemo {
public static void main(String[] args) {
PriorityQueue<String> queue = new PriorityQueue<>(
Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
queue.add("pear");
queue.add("fig");
queue.add("apple");
queue.add("kiwi");
queue.add("date");
StringBuilder out = new StringBuilder();
while (!queue.isEmpty()) {
out.append(queue.poll()).append(' ');
}
System.out.println(out.toString().trim()); // fig date kiwi pear apple
}
}Points to remember:
toString()and the iterator expose the internal heap array. The output is not sorted. Only repeatedpoll()returns sorted order.- The queue is not stable. Elements that compare equal come out in an unspecified order. Add a tie-breaker, like
thenComparingabove, when the order of ties matters. offer,addandpolltake O(log n).peektakes O(1).containsandremove(Object)take O(n) and useequals, not the comparator.nullelements are never allowed, whatever comparator you use.- For a max-heap, pass
Comparator.reverseOrder().
Comparing the three
| Property | TreeSet | TreeMap | PriorityQueue |
|---|---|---|---|
| Ordering applies to | elements | keys | elements |
| Duplicate test | `compare == 0` | `compare == 0` on keys | none, duplicates are allowed |
| `contains` and `remove(Object)` | by comparison, O(log n) | by comparison, O(log n) | by `equals`, O(n) |
| Iteration order | fully sorted | sorted by key | not sorted |
| `null` | only with a null-safe comparator | null key only with a null-safe comparator | never |
| Fixed ordering chosen at | construction | construction | construction |
Natural ordering fails early, and nulls need a comparator
If you build a TreeSet<Object> without a comparator and add something that is not Comparable, you get a ClassCastException. Since Java 7, the first add or put into an empty tree already compares the element with itself. The failure therefore appears at the first insertion, not at the second.
A natural-ordering TreeSet or TreeMap throws NullPointerException on a null element or key, because compareTo cannot be called on null. To allow nulls, wrap the ordering:
import java.util.Comparator;
import java.util.TreeSet;
public class NullTreeDemo {
public static void main(String[] args) {
TreeSet<String> set = new TreeSet<>(
Comparator.nullsFirst(Comparator.<String>naturalOrder()));
set.add("b");
set.add(null);
set.add("a");
System.out.println(set); // [null, a, b]
}
}The ordering must not change while the element is stored
A tree is organized by the comparison results from the moment each element was inserted. If a field used by the comparator changes afterward, the element sits in the wrong place and the tree cannot find it. PriorityQueue has the same problem, since its heap is arranged by the old values.
import java.util.Comparator;
import java.util.TreeSet;
public class MutableKeyDemo {
static class Job {
final String name;
int priority;
Job(String name, int priority) {
this.name = name;
this.priority = priority;
}
@Override
public String toString() {
return name + "=" + priority;
}
}
public static void main(String[] args) {
TreeSet<Job> jobs = new TreeSet<>(
Comparator.comparingInt((Job j) -> j.priority));
Job a = new Job("a", 5);
Job b = new Job("b", 1);
Job c = new Job("c", 3);
jobs.add(a);
jobs.add(b);
jobs.add(c);
b.priority = 9; // changed while stored in the set
System.out.println(jobs); // [b=9, c=3, a=5], not sorted
System.out.println(jobs.size()); // 3
System.out.println(jobs.contains(b)); // false, although b is in the set
System.out.println(jobs.remove(b)); // false, it cannot be removed
}
}The set still holds b, but every search for it follows the new priority down the wrong branch. The safe patterns are:
- Use immutable elements or keys.
- Remove the element, change it, and add it back.
- Rebuild the collection after bulk changes.
Consistency with equals matters here
A comparator that returns 0 for elements that are not interchangeable silently drops data. In the Job example, two jobs with the same priority and different names cannot both be in the TreeSet, because the second add finds a 0 and does nothing. If every job should be kept, add a tie-breaker such as .thenComparing(j -> j.name). The next chapter covers the general rule and the BigDecimal case.
PriorityQueue is the exception. It does not use the ordering to detect duplicates, so equal-priority elements all stay in the queue.
Exercise
A TreeSet<String> is created with new TreeSet<>(Comparator.comparingInt(String::length)). You add "red", "blue", "tan" and "green" in that order. What does the set contain, and why?
Show answer
It contains [red, blue, green]. "tan" has length 3, the same as "red", so the comparator returns 0 and the set treats it as a duplicate and does not add it. The elements are sorted by length, so the order is red (3), blue (4), green (5). Add .thenComparing(Comparator.naturalOrder()) to keep "tan" as well.
Exercise
You put tasks in a PriorityQueue ordered by a mutable deadline field. After adding 100 tasks, you change the deadline of one task already in the queue. Why can poll() now return tasks in the wrong order, and how do you fix it?
Show answer
The heap was arranged using the old deadline. Changing the field does not move the task inside the heap, so the heap's guarantee about the head element no longer holds. To fix it, call remove(task) (which uses equals and costs O(n)), change the deadline, and call add(task) again. Alternatively, make tasks immutable and add a replacement task.