Sub topic 1
Unordered, insertion-ordered and sorted: what order means
Prerequisites
This chapter assumes you know the following:
- How to use maps (dictionaries) and sets.
- Big-O notation for common operations.
- Basic arrays and linked structures.
- How binary search works.
Three meanings of "order"
When you iterate over a collection, the elements come out in some sequence. The collection's contract decides whether you can rely on that sequence. There are three common contracts.
- Unordered: the iteration sequence is unspecified. It may change when you add elements or upgrade the library. Hash maps and hash sets usually work this way.
- Insertion-ordered: iteration follows the order in which keys were first added. Java's
LinkedHashMapand Python'sdictdo this. - Sorted: iteration follows the order of the keys themselves, as defined by a comparison rule. Java's
TreeMapandTreeSetdo this.
Insertion order and sorted order are easy to confuse. Insertion order records history: it depends on when you added each key. Sorted order depends only on the key values. Add the same keys in any sequence and a sorted map gives the same iteration every time.
A worked example
The Java program below puts the same three keys into each kind of map.
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class OrderDemo {
public static void main(String[] args) {
String[] keys = {"pear", "apple", "fig"};
Map<String, Integer> hash = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> sorted = new TreeMap<>();
for (String k : keys) {
hash.put(k, k.length());
linked.put(k, k.length());
sorted.put(k, k.length());
}
System.out.println(hash); // order not guaranteed
System.out.println(linked); // {pear=4, apple=5, fig=3}
System.out.println(sorted); // {apple=5, fig=3, pear=4}
}
}The HashMap line may match one of the others on your machine, but the language does not promise it. Do not write code that depends on it.
Why sorted order costs more
A sorted collection answers questions that the other two cannot answer efficiently. Examples are "what is the smallest key?", "which key comes just below 85?" and "give me every key between 70 and 90". To support these, the collection must keep its keys arranged by comparison, so each insert has to find the right position.
A hash map skips that work. It computes a hash and jumps to a slot, so lookup and insert are O(1) on average. A balanced tree usually needs O(log n) for the same operations. In return you get ordered iteration and navigation by key.
| Contract | Iteration sequence | Typical lookup cost | Typical example |
|---|---|---|---|
| Unordered | Unspecified | O(1) average | `HashMap`, `HashSet` |
| Insertion-ordered | First-added first | O(1) average | `LinkedHashMap`, Python `dict` |
| Sorted | By key comparison | O(log n) | `TreeMap`, `TreeSet` |
An insertion-ordered map is not a sorted map. It cannot find "the key just below 85" without scanning. Later chapters cover the sorted interface and the structures behind it.
Exercise
You insert the keys "pear", "apple" and "fig" into a LinkedHashMap, then insert "banana". What is the iteration order? What would a TreeMap give for the same four insertions?
Show answer
The LinkedHashMap gives pear, apple, fig, banana, because it follows insertion history. The TreeMap gives apple, banana, fig, pear, because it sorts by the keys' natural string order, whatever the insertion sequence.
Exercise
Why is a HashMap a poor choice if you often need the smallest key greater than a given value?
Show answer
A HashMap keeps no relationship between keys, so finding the next larger key requires scanning every key, which costs O(n). A sorted map can answer the same query in O(log n).