Sub topic 14
Ordered Maps: LinkedHashMap and TreeMap
A HashMap finds values fast, but it does not promise any order. When you print it or loop over it, the keys can come out in any order. Sometimes order matters. You may want keys in the order you added them, or in sorted order. Java gives you two maps for this, and both implement the same Map interface you already know.
Three Maps, Three Orders
- HashMap is a map with no guaranteed order.
- LinkedHashMap is a map that remembers insertion order, which is the order you first added the keys.
- TreeMap is a map that keeps its keys in sorted order.
All three use put, get, getOrDefault, and merge in the same way. The only difference is the order of the keys when you loop or print.
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class OrderedMapDemo {
public static void main(String[] args) {
Map<String, Integer> hash = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> tree = new TreeMap<>();
String[] fruits = {"pears", "apples", "oranges"};
int[] counts = {4, 10, 7};
for (int i = 0; i < fruits.length; i++) {
hash.put(fruits[i], counts[i]);
linked.put(fruits[i], counts[i]);
tree.put(fruits[i], counts[i]);
}
System.out.println(hash); // order not guaranteed
System.out.println(linked); // {pears=4, apples=10, oranges=7}
System.out.println(tree); // {apples=10, oranges=7, pears=4}
linked.put("pears", 99); // update an existing key
System.out.println(linked); // {pears=99, apples=10, oranges=7}
}
}The last line shows a detail worth knowing. If you put a key that is already in a LinkedHashMap, the value changes but the key keeps its first position.
Extra Powers of TreeMap
A TreeMap sorts keys by their natural order. For strings that means alphabetical order, and for numbers it means smallest first. Because the keys are sorted, a TreeMap can answer questions that a HashMap cannot:
firstKey()returns the smallest key.lastKey()returns the largest key.floorKey(k)returns the largest key that is less than or equal tok.
To use these methods, declare the variable as TreeMap rather than Map. You can also pass a Comparator to the constructor to choose a different order.
import java.util.Comparator;
import java.util.TreeMap;
public class TreeMapExtras {
public static void main(String[] args) {
TreeMap<Integer, String> grades = new TreeMap<>();
grades.put(90, "A");
grades.put(80, "B");
grades.put(70, "C");
System.out.println(grades.firstKey()); // 70
System.out.println(grades.lastKey()); // 90
System.out.println(grades.floorKey(85)); // 80
System.out.println(grades.get(grades.floorKey(85))); // B
TreeMap<String, Integer> reversed = new TreeMap<>(Comparator.reverseOrder());
reversed.put("apples", 10);
reversed.put("pears", 4);
reversed.put("oranges", 7);
System.out.println(reversed); // {pears=4, oranges=7, apples=10}
}
}The floorKey(85) call turns a score into a grade. A score of 85 falls in the 80 band, so the result is "B".
Comparing the Three
| Map | Key order | Speed of get and put | Null key allowed |
|---|---|---|---|
| HashMap | None guaranteed | Fastest | Yes |
| LinkedHashMap | Insertion order | Fast, uses a bit more memory | Yes |
| TreeMap | Sorted | Slower on large maps | No |
Use HashMap by default. Switch to LinkedHashMap when output should follow the order you added items. Switch to TreeMap when you need sorted keys or methods like firstKey.
Exercise
You add the keys "zebra", "ant", and "mole" (in that order) to a LinkedHashMap and to a TreeMap. What key order does each map print?
Show answer
The LinkedHashMap prints zebra, ant, mole, which is the insertion order. The TreeMap prints ant, mole, zebra, which is alphabetical order.
Exercise
A TreeMap<Integer, String> holds the keys 0, 50, and 100. What does floorKey(75) return, and why?
Show answer
It returns 50. The floorKey method gives the largest key that is less than or equal to 75. Of the keys 0, 50, and 100, the value 50 is the largest one that does not go above 75.