Sub topic 14
Ordered Maps: LinkedHashMap and TreeMap
A HashMap finds values fast, but it makes no promise about order. If you print one, the keys can come out in any order. That order can even change when you add more keys. Sometimes you need a fixed order, for example in a report or a menu.
Java gives you two other maps for this:
LinkedHashMapis a map that remembers the order in which you added keys.TreeMapis a map that keeps its keys sorted.
Both implement the same Map interface you already know. You still use put, get, getOrDefault, merge, and entrySet. The only thing that changes is the order of the keys.
Two Kinds of Order
These two words mean different things:
- Insertion order is the order in which keys were first added.
LinkedHashMapuses it. - Sorted order follows a rule, such as alphabetical order for strings or smallest-first for numbers.
TreeMapuses it.
The diagram shows the same three put calls going into each type of map.
LinkedHashMap: Keeps Insertion Order
You create a LinkedHashMap the same way you create a HashMap. When you print it or loop over it, the keys come out in the order you added them.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class OrderDemo {
public static void main(String[] args) {
Map<String, Integer> linked = new LinkedHashMap<>();
linked.put("pears", 4);
linked.put("apples", 10);
linked.put("oranges", 7);
System.out.println(linked); // {pears=4, apples=10, oranges=7}
// Putting an existing key again changes the value, not the position
linked.put("pears", 5);
System.out.println(linked); // {pears=5, apples=10, oranges=7}
// Removing a key and adding it back moves it to the end
linked.remove("pears");
linked.put("pears", 5);
System.out.println(linked); // {apples=10, oranges=7, pears=5}
// Copy into a TreeMap to get sorted order
Map<String, Integer> tree = new TreeMap<>(linked);
System.out.println(tree); // {apples=10, oranges=7, pears=5}
}
}Look at the second put("pears", 5). The key pears was already in the map, so Java only replaced its value. The key stayed in first place. A key moves to the end only if you remove it and add it again.
How it keeps the order
Inside, a LinkedHashMap is a HashMap with one extra feature. Every entry also holds links to the entry added before it and the entry added after it. Those links form a chain. Lookups still go through the fast hash table, and loops follow the chain. This makes LinkedHashMap about as fast as HashMap. It uses a little more memory for the links.
Access order and a small cache
LinkedHashMap has a second mode called access order. In this mode, every time you read a key with get, that key moves to the end of the chain. The key at the front is then the one used least recently.
You can use this to build an LRU cache. LRU means "least recently used." It is a store with a size limit, and when it gets full it removes the entry nobody has used for the longest time. The method removeEldestEntry runs after each put. If it returns true, the map removes the oldest entry.
import java.util.LinkedHashMap;
import java.util.Map;
public class CacheDemo {
static class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
LruCache(int capacity) {
// 16 = starting size, 0.75f = load factor, true = access order
super(16, 0.75f, true);
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
public static void main(String[] args) {
LruCache<String, Integer> cache = new LruCache<>(2);
cache.put("a", 1);
cache.put("b", 2);
cache.get("a"); // "a" becomes the most recently used
cache.put("c", 3); // over capacity: "b" is removed
System.out.println(cache); // {a=1, c=3}
}
}TreeMap: Keeps Keys Sorted
A TreeMap sorts its keys every time you add one. By default it uses natural order. For strings, natural order is alphabetical, and uppercase letters come before lowercase ones. For numbers, it is smallest first. The key type must implement Comparable, which is how a class defines its natural order.
How it keeps the order
Inside, a TreeMap is a red-black tree, a kind of tree that keeps itself balanced. Each key sits in a node. Smaller keys go to the left and larger keys go to the right. Finding a key means walking down from the top of the tree. That takes about log₂(n) steps, which is roughly 20 steps for a million keys. This is slower than a HashMap, but it is still fast.
Asking questions about order
Because its keys are sorted, a TreeMap can answer questions that a HashMap cannot. To use these methods, declare the variable as TreeMap and not as Map. The plain Map interface does not include them.
import java.util.TreeMap;
public class GradeDemo {
public static void main(String[] args) {
// Key = lowest score for the grade, value = the grade
TreeMap<Integer, String> grades = new TreeMap<>();
grades.put(90, "A");
grades.put(80, "B");
grades.put(70, "C");
grades.put(60, "D");
grades.put(0, "F");
System.out.println(grades.floorEntry(85).getValue()); // B
System.out.println(grades.ceilingKey(75)); // 80
System.out.println(grades.firstKey()); // 0
System.out.println(grades.lastKey()); // 90
System.out.println(grades.headMap(70)); // {0=F, 60=D}
System.out.println(grades.tailMap(80)); // {80=B, 90=A}
System.out.println(grades.descendingMap()); // {90=A, 80=B, 70=C, 60=D, 0=F}
}
}The table describes each method.
| Method | What it returns |
|---|---|
| `firstKey()` / `lastKey()` | The smallest or largest key |
| `floorKey(k)` / `floorEntry(k)` | The largest key that is less than or equal to `k` |
| `ceilingKey(k)` | The smallest key that is greater than or equal to `k` |
| `headMap(k)` | All entries with keys below `k`. The key `k` itself is not included |
| `tailMap(k)` | All entries with keys from `k` upward. The key `k` itself is included |
| `descendingMap()` | A view of the map in reverse order |
The grade example shows a common use for floorEntry. A score of 85 has no exact key in the map. floorEntry(85) returns the entry for 80, the closest key below 85, so the grade is B.
Using your own sort rule
You can pass a Comparator to the constructor. A comparator is an object that decides which of two values comes first. The TreeMap then sorts with that rule and ignores natural order.
import java.util.Comparator;
import java.util.TreeMap;
public class ComparatorMapDemo {
public static void main(String[] args) {
TreeMap<String, Integer> byLength = new TreeMap<>(
Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
byLength.put("banana", 1);
byLength.put("fig", 2);
byLength.put("kiwi", 3);
System.out.println(byLength); // {fig=2, kiwi=3, banana=1}
TreeMap<String, Integer> noCase = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
noCase.put("apple", 1);
noCase.put("Banana", 2);
noCase.put("APPLE", 3);
System.out.println(noCase); // {apple=3, Banana=2}
}
}The second map is surprising at first. A TreeMap does not use equals to decide whether two keys are the same. It asks the comparator instead. When the comparator says two keys are equal, the map treats them as one key. The case-insensitive comparator says "APPLE" equals "apple", so the third put replaced the value. The map kept the original key, "apple".
Gotchas to Watch For
- Null keys.
HashMapandLinkedHashMapaccept onenullkey. ATreeMapwith natural order throwsNullPointerExceptionif you add anullkey, because it cannot comparenullwith other keys. - Keys that cannot be compared. If the key class does not implement
Comparableand you gave no comparator, the firstputthrowsClassCastException. - Changing a key after you add it. If a key's fields change after it goes into a
TreeMap, the key ends up in the wrong place in the tree, and lookups stop finding it. The same rule applies to hash keys. Use immutable keys, such asString,Integer, or your own class withfinalfields. - Sorting by value. A
TreeMapsorts only by key. To order entries by value, copy the entries into a list and sort that list.
Side-by-Side Comparison
| Feature | HashMap | LinkedHashMap | TreeMap |
|---|---|---|---|
| Order of keys | Not guaranteed | Insertion order (or access order) | Sorted by key |
| Speed of `get` and `put` | Very fast, about constant time | Very fast, about constant time | Fast, grows with log of size |
| `null` key allowed | Yes, one | Yes, one | No, with natural order |
| Key requirement | `equals` and `hashCode` | `equals` and `hashCode` | `Comparable` or a `Comparator` |
| Range methods like `floorKey` | No | No | Yes |
If order does not matter, use HashMap. If you want keys back in the order you added them, use LinkedHashMap. If you need sorted keys or range questions such as "the closest key below 85", use TreeMap.
Exercise
You add the keys "cherry", "apple", "banana" (in that order) to a LinkedHashMap and to a TreeMap. Then you call put("cherry", 99) on both. What does printing each map show for key order?
Show answer
The LinkedHashMap shows cherry, apple, banana. Putting an existing key only replaces its value and does not move the key. The TreeMap shows apple, banana, cherry, because it always sorts by key. In both maps, cherry now has the value 99.
Exercise
A shipping company charges by weight. Packages from 0 kg cost 5, from 2 kg cost 9, and from 10 kg cost 20. Which TreeMap method finds the price for a 7 kg package, and what does it return?
Show answer
Store the prices in a TreeMap<Integer, Integer> with keys 0, 2, and 10. Then call floorEntry(7).getValue(). The largest key at or below 7 is 2, so the method returns 9.
Exercise
Why does new TreeMap<String, Integer>(Comparator.comparing(String::length)) lose data when you put "kiwi" and then "pear"?
Show answer
A TreeMap uses the comparator to decide whether two keys are the same key. Both words have length 4, so the comparator returns 0 and the map treats them as one key. The second put replaces the value of "kiwi". Add a tie-breaker, such as thenComparing(Comparator.naturalOrder()), to keep both keys.