LinkedHashMap and TreeMap
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)HashMap is fast but keeps no order. Two other maps fix that: LinkedHashMap remembers the order in which keys were added, and TreeMap keeps the keys sorted. Both implement Map, so put, get and the loops work exactly as before.
LinkedHashMap: insertion order
LinkedHashMap is a HashMap that also links its entries in a list, so a loop gives them back in the order they were added (insertion order). get and put stay O(1); the list costs a little extra memory.
A HashMap keeps no order. A LinkedHashMap remembers the order in which keys were added, so a loop follows the put calls. Below, the same five products are stored in three map types.
Example 1 · Same data, three maps
import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;import java.util.TreeMap;
public class ThreeMapsDemo { public static void main(String[] args) { String[] items = {"Pen", "Eraser", "Notebook", "Stapler", "Marker"}; int[] prices = {10, 15, 40, 30, 20};
Map<String, Integer> hash = new HashMap<>(); Map<String, Integer> linked = new LinkedHashMap<>(); Map<String, Integer> tree = new TreeMap<>();
for (int i = 0; i < items.length; i++) { hash.put(items[i], prices[i]); linked.put(items[i], prices[i]); tree.put(items[i], prices[i]); } linked.put("Pen", 12);
System.out.println("HashMap: " + hash); System.out.println("LinkedHashMap: " + linked); System.out.println("TreeMap: " + tree); }}HashMap: {Notebook=40, Pen=10, Stapler=30, Marker=20, Eraser=15}
LinkedHashMap: {Pen=12, Eraser=15, Notebook=40, Stapler=30, Marker=20}
TreeMap: {Eraser=15, Marker=20, Notebook=40, Pen=10, Stapler=30}What this code does
- The
HashMaporder comes from the buckets and is not promised. - The
LinkedHashMapkeeps the order of theputcalls. Changing Pen's price to 12 kept Pen in first place. - The
TreeMapsorts the keys alphabetically, whatever order they were added in.
Putting a new value for an existing key does not move that key: it keeps its old place. Only a key that is removed and added again goes to the end.
LinkedHashMap whenever output order matters but sorting does not: a product catalog in the order the owner typed it, a batting order, a form's fields.TreeMap: sorted keys
TreeMap is a map that keeps its keys sorted, by natural order or by a Comparator. It is built on a balanced tree, so get, put and remove take O(log n), and it adds methods like firstKey and floorKey.
A TreeMap keeps its keys in sorted order: numbers small to big, strings in dictionary order. Below, one contact book is shown in natural, case-insensitive and reverse order; then a key that cannot be sorted fails.
Example 2 · TreeMap with a Comparator
import java.util.Comparator;import java.util.Map;import java.util.TreeMap;
public class ContactOrderDemo { public static void main(String[] args) { Map<String, String> plain = new TreeMap<>(); Map<String, String> ignoreCase = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); Map<String, String> reverse = new TreeMap<>(Comparator.reverseOrder());
String[] names = {"arjun", "Bhavna", "Riya", "riya", "Kabir"}; String[] phones = {"98450", "99001", "90080", "90081", "97412"}; for (int i = 0; i < names.length; i++) { plain.put(names[i], phones[i]); ignoreCase.put(names[i], phones[i]); reverse.put(names[i], phones[i]); }
System.out.println("Natural: " + plain); System.out.println("Ignore case: " + ignoreCase); System.out.println("Reverse: " + reverse); }}Natural: {Bhavna=99001, Kabir=97412, Riya=90080, arjun=98450, riya=90081}
Ignore case: {arjun=98450, Bhavna=99001, Kabir=97412, Riya=90081}
Reverse: {riya=90081, arjun=98450, Riya=90080, Kabir=97412, Bhavna=99001}What this code does
- Natural
Stringorder puts all capital letters before small ones, soarjunandriyacome last. - With
String.CASE_INSENSITIVE_ORDER,Riyaandriyacompare as equal, so they are one key: the secondputreplaced the phone number but kept the first spelling. Comparator.reverseOrder()sorts the keys from Z to A.
Example 3 · Mistake: a key class that cannot be sorted
import java.util.Map;import java.util.TreeMap;
class Student { String name;
Student(String name) { this.name = name; }}
public class TreeMapKeyDemo { public static void main(String[] args) { Map<Student, Integer> marks = new TreeMap<>(); marks.put(new Student("Riya"), 88); System.out.println(marks); }}Exception in thread "main" java.lang.ClassCastException: class Student cannot be cast to class java.lang.Comparable (Student is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap') at java.base/java.util.TreeMap.compare(TreeMap.java:1569) at java.base/java.util.TreeMap.addEntryToEmptyMap(TreeMap.java:776) at java.base/java.util.TreeMap.put(TreeMap.java:785) at java.base/java.util.TreeMap.put(TreeMap.java:534) at TreeMapKeyDemo.main(TreeMapKeyDemo.java:15)
What this code does
- A
TreeMapmust compare keys to place them.Studentdoes not implementComparable, so the very firstputfails. - Fix it by making
StudentimplementComparable<Student>, or by passing a comparator:new TreeMap<>((a, b) -> a.name.compareTo(b.name)).
To sort, the keys must be Comparable (like String and Integer), or you pass a Comparator to the constructor: new TreeMap<>(Comparator.reverseOrder()). A key class that is neither causes a ClassCastException. A null key causes a NullPointerException.
Predict the output
In which order does a TreeMap print?
Read each program and pick what it prints.
Round 1 of 3
Names with capital and small letters.
TreeMap uses compareTo (or the comparator), not equals, to decide if two keys are the same. With String.CASE_INSENSITIVE_ORDER, "riya" and "Riya" are one key.Moving around a TreeMap
floorKey(k) is the biggest key that is less than or equal to k. ceilingKey(k) is the smallest key that is greater than or equal to k. Both return null when there is no such key.
Because the keys are sorted, a TreeMap can answer "what is the nearest key?". Below, floorEntry turns marks into grade bands, and a train timetable finds the next and the previous train.
Example 4 · Grade bands with floorEntry
import java.util.Map;import java.util.TreeMap;
public class GradeBandDemo { public static void main(String[] args) { TreeMap<Integer, String> cutoff = new TreeMap<>(); cutoff.put(0, "F"); cutoff.put(35, "C"); cutoff.put(60, "B"); cutoff.put(75, "A"); cutoff.put(90, "A+");
int[] marks = {34, 35, 59, 76, 90, 100}; for (int m : marks) { Map.Entry<Integer, String> band = cutoff.floorEntry(m); System.out.println(m + " -> " + band.getValue() + " (band starts at " + band.getKey() + ")"); } }}34 -> F (band starts at 0) 35 -> C (band starts at 35) 59 -> C (band starts at 35) 76 -> A (band starts at 75) 90 -> A+ (band starts at 90) 100 -> A+ (band starts at 90)
What this code does
- The keys are the lowest marks of each band.
floorEntry(76)finds the biggest key that is ≤ 76, which is 75, so the grade is A. - No
if-elseladder is needed. To change a band, change oneputline. - The variable type is
TreeMap, notMap, becausefloorEntryexists only on sorted maps.
Example 5 · A train timetable: next and previous
import java.util.TreeMap;
public class TimetableDemo { public static void main(String[] args) { TreeMap<String, String> trains = new TreeMap<>(); trains.put("06:10", "Shatabdi Express"); trains.put("09:45", "Intercity Express"); trains.put("13:20", "Passenger 56512"); trains.put("17:05", "Vande Bharat"); trains.put("21:30", "Mail Express");
String now = "10:15"; System.out.println("First train: " + trains.firstKey() + " " + trains.get(trains.firstKey())); System.out.println("Last train: " + trains.lastKey() + " " + trains.get(trains.lastKey())); System.out.println("Next after " + now + ": " + trains.ceilingEntry(now)); System.out.println("Missed: " + trains.floorEntry(now)); System.out.println("Already left: " + trains.headMap(now).keySet()); System.out.println("Still to come: " + trains.tailMap(now).keySet()); System.out.println("After 21:30: " + trains.higherKey("21:30")); }}First train: 06:10 Shatabdi Express Last train: 21:30 Mail Express Next after 10:15: 13:20=Passenger 56512 Missed: 09:45=Intercity Express Already left: [06:10, 09:45] Still to come: [13:20, 17:05, 21:30] After 21:30: null
What this code does
- Times written as
HH:MMwith two digits sort correctly as strings, so theTreeMapkeeps them in time order. ceilingEntry("10:15")gives the first train at or after 10:15;floorEntrygives the last one at or before it.headMapandtailMapsplit the timetable at the current time.higherKeyreturnsnullwhen there is no later train.
The ...Key methods return a key and the ...Entry methods return a whole entry. Also: firstKey() and lastKey(); lowerKey(k) (biggest key < k) and higherKey(k) (smallest key > k); headMap(k) (keys < k), tailMap(k) (keys >= k) and subMap(a, b) (from a up to, not including, b).
Access order: a tiny LRU cache
Access order is a LinkedHashMap mode where every get or put of a key moves it to the end. The first entry is then always the one used longest ago, which is the idea behind an LRU cache.
new LinkedHashMap<>(16, 0.75f, true) keeps access order. Below, a "recently viewed products" list keeps only the latest three items: opening a product moves it to the end, and a new one pushes the oldest out.
Example 6 · Recently viewed products: an LRU cache
import java.util.LinkedHashMap;import java.util.Map;
public class RecentlyViewedDemo { public static void main(String[] args) { final int MAX = 3; Map<String, Integer> recent = new LinkedHashMap<>(16, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) { return size() > MAX; } };
recent.put("Phone", 15999); recent.put("Earbuds", 1299); recent.put("Charger", 799); System.out.println("Viewed 3: " + recent.keySet());
recent.get("Phone"); System.out.println("Opened Phone: " + recent.keySet());
recent.put("Cover", 299); System.out.println("Viewed Cover: " + recent.keySet()); }}Viewed 3: [Phone, Earbuds, Charger] Opened Phone: [Earbuds, Charger, Phone] Viewed Cover: [Charger, Phone, Cover]
What this code does
- The third constructor argument
trueturns on access order:get("Phone")moved Phone to the end, the "most recent" side. - The anonymous subclass overrides
removeEldestEntry. Afterput("Cover")the size became 4, so the map removed its eldest entry, Earbuds, the product used longest ago.
An LRU cache (Least Recently Used) is a small store that keeps only the latest few items. Override removeEldestEntry to return true when the map is too big, and the map drops its oldest entry by itself after each put. The next lesson, Build an LRU cache with LinkedHashMap (opens in a new tab), builds one step by step.
Which map should you pick?
Start with HashMap. Switch only when you need something it does not give:
Map<String, Integer> fees = new HashMap<>(); // fastest, no orderMap<String, Integer> visits = new LinkedHashMap<>(); // insertion orderMap<String, Integer> recent = new LinkedHashMap<>(16, 0.75f, true); // access order (LRU)TreeMap<Integer, String> bands = new TreeMap<>(); // sorted keys, floorEntryHashMap: fastest, O(1); no order. The default choice.LinkedHashMap: O(1); insertion order (or access order for an LRU cache).TreeMap: O(log n); sorted keys plus floor, ceiling, head and tail lookups.EnumMap: when the keys are constants of oneenum; very fast, kept in the enum's order.
Keys that are the constants of one enum have a map of their own: EnumMap and EnumSet (opens in a new tab) shows when to use it instead of a HashMap.
Next step
Check your understanding
12 quick questions