Sub topic 13
Ordering Guarantees and SplayTreeMap/SplayTreeSet
This chapter assumes that you know Dart generics, collection literals, List, Map, Set, and basic iteration. You should also be familiar with null safety and importing Dart libraries.
Dart’s built-in collection types have different ordering guarantees. A map literal preserves the order in which entries are added. A regular set usually preserves insertion order, but code should not depend on sorted order. Use SplayTreeMap or SplayTreeSet when iteration must follow key or element order.
Insertion order versus sorted order
A regular map keeps insertion order:
void main() {
final prices = {'banana': 2, 'apple': 3, 'pear': 4};
for (final entry in prices.entries) {
print('${entry.key}: ${entry.value}');
}
}This prints the entries in the order banana, apple, pear. The keys are not sorted alphabetically.
A SplayTreeMap keeps its keys sorted according to a comparison function. The default comparison works for keys that implement a suitable ordering, such as strings and numbers.
import 'dart:collection';
void main() {
final prices = SplayTreeMap<String, int>();
prices['banana'] = 2;
prices['apple'] = 3;
prices['pear'] = 4;
for (final entry in prices.entries) {
print('${entry.key}: ${entry.value}');
}
}The output is ordered as apple, banana, and pear, even though the entries were inserted in another order.
| Collection | Main ordering behavior | Typical use |
|---|---|---|
| `Map` literal | Insertion order | Preserve the order received |
| `SplayTreeMap` | Sorted by key | Iterate through keys in order |
| `SplayTreeSet` | Sorted by element | Keep unique values sorted |
SplayTreeMap
Import dart:collection to use SplayTreeMap. You can also provide a comparison function. The function should return a negative value when the first value comes before the second, zero when they are equivalent for ordering, and a positive value when it comes after.
import 'dart:collection';
void main() {
final scores = SplayTreeMap<String, int>(
(a, b) => a.length.compareTo(b.length),
);
scores['cat'] = 3;
scores['elephant'] = 8;
scores['ox'] = 2;
print(scores.keys); // (ox, cat, elephant)
}This map sorts keys by length. However, this comparison has an important problem: two different keys with the same length compare as equal. For example, "cat" and "dog" both have length three. A sorted map may treat the second insertion as a replacement rather than as a separate key.
A comparison function used by a sorted map should distinguish every key that must remain separate.
SplayTreeSet
SplayTreeSet stores unique values in sorted order.
import 'dart:collection';
void main() {
final numbers = SplayTreeSet<int>();
numbers.addAll([7, 2, 9, 2, 4]);
print(numbers); // {2, 4, 7, 9}
print(numbers.first); // 2
print(numbers.last); // 9
}The duplicate 2 is ignored. The set supports normal set operations, while its iteration order follows the comparator.
Internally, a splay tree is a self-adjusting binary search tree. Accessed nodes move closer to the root. Individual operations can take longer, but common operations have amortized logarithmic performance. Use a splay tree for ordered access, not because it is always faster than a hash-based collection.
Choosing an ordered collection
Use a normal Map or Set when insertion order or fast hash-based lookup is enough. Use SplayTreeMap when you need sorted keys during iteration. Use SplayTreeSet when you need unique, sorted values.
Exercise
What happens if a SplayTreeSet comparator returns zero for two distinct values?
Show answer
The set treats them as equivalent for ordering and keeps only one of them.