Sub topic 13
Ordering Guarantees and SplayTreeMap/SplayTreeSet
This chapter covers what order Dart's collections promise when you iterate them, and how to get sorted iteration with SplayTreeMap and SplayTreeSet. It assumes you can write basic Dart, read generics such as Map<String, int>, and already know how to create lists, maps, and sets. You should also know that iterating a collection visits its elements one at a time.
What "order" means for each collection
A collection can make three kinds of ordering promise:
- Index order. Elements sit at positions 0, 1, 2, and so on. Only
Listpromises this. - Insertion order. Iteration visits elements in the order they were first added.
- Sorted order. Iteration visits elements in the order of a comparison, whatever order you added them in.
Which promise you get depends on the concrete class behind the literal.
| Class | Created by | Iteration order |
|---|---|---|
| `List` | `[1, 2]` | Index order |
| `LinkedHashMap` | `{'a': 1}` and `Map()` | Insertion order |
| `LinkedHashSet` | `{1, 2}` and `Set()` | Insertion order |
| `HashMap`, `HashSet` | `dart:collection` constructors | No guarantee |
| `SplayTreeMap`, `SplayTreeSet` | `dart:collection` constructors | Sorted by the compare function |
The static type of a map literal is Map, but the object is a LinkedHashMap. The same holds for set literals and LinkedHashSet. That is why the following code is safe to rely on.
Insertion order in literals
Map and set literals keep insertion order. Two rules cause most of the surprises:
- Assigning to an existing key replaces the value but keeps the key's original position.
- Removing a key and adding it again puts it at the end.
void main() {
final scores = <String, int>{'b': 2, 'a': 1};
scores['c'] = 3;
scores['b'] = 20; // existing key keeps its position
print(scores); // {b: 20, a: 1, c: 3}
scores.remove('b');
scores['b'] = 2; // re-added keys go to the end
print(scores.keys.toList()); // [a, c, b]
final tags = <String>{'x', 'y'};
tags.add('x'); // already present, nothing changes
tags.remove('x');
tags.add('x');
print(tags); // {y, x}
}Sets follow the same rule. Adding a duplicate does not move the existing element.
When insertion order is not enough
Insertion order is a record of history, not a sort. If you add 'b' and then 'a', the map iterates b, a. To iterate in alphabetical order you have two choices:
- Sort at read time with
keys.toList()..sort(). This is simple and fine if you iterate rarely. - Keep the data sorted all the time with a
SplayTreeMaporSplayTreeSet.
SplayTreeMap and SplayTreeSet
Both classes live in dart:collection, so you must import it. They store elements in a self-balancing binary search tree. Iteration always visits keys from smallest to largest, regardless of insertion order.
import 'dart:collection';
void main() {
final m = {'b': 2, 'a': 1};
final sorted = SplayTreeMap<String, int>.from(m);
sorted['c'] = 3;
sorted['aa'] = 4;
print(sorted.keys); // (a, aa, b, c)
print(sorted); // {a: 1, aa: 4, b: 2, c: 3}
}SplayTreeMap.from copies an existing map. The result is a new, independent map. You can also start empty with SplayTreeMap<K, V>() and add entries.
The default comparison
With no compare function, the tree orders keys with Comparable.compare, which calls compareTo. Numbers, strings, and DateTime all work. A key type that does not implement Comparable fails at runtime with a type error, not when you compile. You fix this by passing your own compare function.
Custom ordering
The first constructor argument is a compare function. It returns a negative number if the first argument sorts first, zero if they are equal, and a positive number otherwise. Swapping the arguments gives descending order.
import 'dart:collection';
void main() {
final desc = SplayTreeSet<int>((a, b) => b.compareTo(a))
..addAll([3, 1, 2]);
print(desc); // {3, 2, 1}
final byLength = SplayTreeMap<String, int>(
(a, b) => a.length.compareTo(b.length),
);
byLength['kiwi'] = 1;
byLength['fig'] = 2;
byLength['banana'] = 3;
print(byLength.keys); // (fig, kiwi, banana)
}The comparator also defines equality
This is the most common bug with these classes. A hash-based set decides whether two elements are the same with == and hashCode. A SplayTreeSet or SplayTreeMap does not use those. It treats two elements as the same when the compare function returns 0.
import 'dart:collection';
void main() {
final byLower = SplayTreeSet<String>(
(a, b) => a.toLowerCase().compareTo(b.toLowerCase()),
);
print(byLower.add('Apple')); // true
print(byLower.add('apple')); // false, compare returned 0
print(byLower); // {Apple}
final byLength = SplayTreeMap<String, int>(
(a, b) => a.length.compareTo(b.length),
);
byLength['cat'] = 1;
byLength['dog'] = 2; // same length, so same key
print(byLength); // {cat: 2}
}In the last map, 'dog' is not added as a second key. The value for the existing key 'cat' is replaced, and the key stays 'cat'. If you sort by one field of an object but need to keep objects that differ in other fields, make the comparator break ties on the remaining fields.
Custom classes
Here a Version class is ordered by major number, then by minor number. The tie-breaker means two different versions never compare as 0.
import 'dart:collection';
class Version {
final int major;
final int minor;
const Version(this.major, this.minor);
@override
String toString() => '$major.$minor';
}
int compareVersions(Version a, Version b) {
final byMajor = a.major.compareTo(b.major);
return byMajor != 0 ? byMajor : a.minor.compareTo(b.minor);
}
void main() {
final releases = SplayTreeSet<Version>(compareVersions)
..add(const Version(2, 0))
..add(const Version(1, 5))
..add(const Version(1, 2));
print(releases); // {1.2, 1.5, 2.0}
print(releases.first); // 1.2
print(releases.last); // 2.0
}The class does not need to override == or hashCode for this to work, because the tree never calls them. If you later move the same objects into a regular Set, you do need them (see the equality chapter).
Navigating a sorted map
A sorted structure answers questions that insertion-ordered ones cannot answer cheaply. SplayTreeMap has methods for reading the smallest and largest keys and for finding the neighbors of a key.
import 'dart:collection';
void main() {
final prices = SplayTreeMap<int, String>();
prices[300] = 'large';
prices[100] = 'small';
prices[200] = 'medium';
print(prices.firstKey()); // 100
print(prices.lastKey()); // 300
print(prices.firstKeyAfter(150)); // 200
print(prices.lastKeyBefore(150)); // 100
print(prices.firstKeyAfter(300)); // null
}firstKey, lastKey, firstKeyAfter, and lastKeyBefore return a nullable key. They return null when the map is empty or no key qualifies, so handle that with ? or ??. The probe key (150 above) does not have to be in the map. A SplayTreeSet offers first and last, which throw a StateError on an empty set.
Costs and trade-offs
| Operation | Hash-based map or set | Splay tree |
|---|---|---|
| Lookup, add, remove | Constant time on average | O(log n), amortized |
| Iterate in sorted order | Needs a sort first | Already sorted |
| Smallest or largest key | Scan everything | Direct |
| Keys need | `==` and `hashCode` | A consistent comparison |
A splay tree reorganizes itself on access, moving recently used keys toward the root. Reads can therefore change the tree's internal shape. This never changes the iteration order. It does mean that frequent lookups of a few keys are cheap, while a very large map still pays the logarithmic cost.
Choose a splay tree when you repeatedly need sorted iteration, a range-style query, or the nearest key. For a plain lookup table, the default literal is faster and simpler. If you need sorted output once at the end, sort a copy of the keys instead.
Failure modes
- Changing a key after insertion. If a key's comparison value changes while it is in the tree, the tree's order becomes wrong. Lookups can miss it and removal can fail. Use immutable keys, or remove the element, change it, and add it again.
- An inconsistent comparator. A compare function must give the same answer for the same pair and agree with itself transitively. Random or time-dependent comparators produce unpredictable behavior.
- Modifying while iterating. Adding or removing during a
forloop over any of these collections throwsConcurrentModificationError. Iterate over a copy such askeys.toList()when you need to change the collection. - Comparing values that cannot be compared. Calling
compareToonnullor on mixed types throws at runtime. The default comparator is only safe for one consistent, non-null key type. - Assuming
HashMaporder. Code that works by accident with aHashMapcan reorder after a Dart upgrade. If order matters, use the literal or a splay tree.
Exercise
A SplayTreeSet<String> is created with the comparator (a, b) => a.length.compareTo(b.length). You add 'pear', 'plum', and 'fig' in that order. What does it contain, and why?
Show answer
It contains {pear, fig}. 'plum' has the same length as 'pear', so the comparator returns 0 and the set treats it as a duplicate. add returns false and 'pear' stays. 'fig' is shorter, so it sorts first and the printed set is {fig, pear}.
Exercise
A map literal holds {'x': 1, 'y': 2, 'z': 3}. You run m['x'] = 10, then m.remove('y'), then m['y'] = 20. In what order do the keys iterate?
Show answer
x, z, y. Assigning to 'x' keeps its position. Removing 'y' and adding it again moves it to the end.
Exercise
You keep event timestamps (as int keys) in a SplayTreeMap<int, String>. How do you find the first event strictly after time t, and what must your code handle?
Show answer
Call events.firstKeyAfter(t). It returns an int?, so handle null, which means no later event exists. Then read events[key] if the key is not null.