HashMap is the default map in Java, but it makes no promise about order. When you need keys sorted, or kept in the order they were added, or you want to find “the nearest key below 74”, you need its two relatives: TreeMap and LinkedHashMap. This lesson compares the three, shows TreeMap’s powerful navigation methods, and builds a working LRU cache with a LinkedHashMap in a few lines.
In this lesson you will learn
- How HashMap, LinkedHashMap and TreeMap order their keys
- Counting with
merge - TreeMap navigation:
floorEntry,headMap,tailMap,higherKey - Access-ordered LinkedHashMap and
removeEldestEntry - Choosing the right map for the job
You should know HashMap and generics.
Three Maps, Three Orders
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] cities = {"Sylhet", "Dhaka", "Khulna", "Barishal", "Dhaka", "Rajshahi"};
Map<String, Integer> hash = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> tree = new TreeMap<>();
for (String c : cities) {
hash.merge(c, 1, Integer::sum);
linked.merge(c, 1, Integer::sum);
tree.merge(c, 1, Integer::sum);
}
System.out.println("LinkedHashMap (insertion order): " + linked);
System.out.println("TreeMap (sorted by key) : " + tree);
System.out.println("HashMap has same entries? " + hash.equals(tree));
// TreeMap navigation methods
TreeMap<Integer, String> grades = new TreeMap<>(Map.of(
80, "A+", 70, "A", 60, "A-", 50, "B", 40, "C", 33, "D", 0, "F"));
int[] marks = {92, 74, 59, 33, 12};
for (int m : marks) {
System.out.println(m + " -> " + grades.floorEntry(m).getValue());
}
System.out.println("first key " + grades.firstKey() + ", last key " + grades.lastKey());
System.out.println("keys from 50 up : " + grades.tailMap(50).keySet());
System.out.println("keys below 50 : " + grades.headMap(50).keySet());
System.out.println("next key above 60: " + grades.higherKey(60));
}
}
Output
LinkedHashMap (insertion order): {Sylhet=1, Dhaka=2, Khulna=1, Barishal=1, Rajshahi=1}
TreeMap (sorted by key) : {Barishal=1, Dhaka=2, Khulna=1, Rajshahi=1, Sylhet=1}
HashMap has same entries? true
92 -> A+
74 -> A
59 -> B
33 -> D
12 -> F
first key 0, last key 80
keys from 50 up : [50, 60, 70, 80]
keys below 50 : [0, 33, 40]
next key above 60: 70
merge(key, 1, Integer::sum)puts 1 for a new key, or adds 1 to the existing count. Dhaka appears twice.LinkedHashMapremembers insertion order: Sylhet first, as it was added first.TreeMapkeeps keys sorted: Barishal, Dhaka, Khulna, and so on.- All three hold the same entries;
equalscompares contents, not order.HashMap‘s own order is unpredictable, so it is not printed here.
The grade table shows why TreeMap is special. floorEntry(74) finds the largest key that is ≤ 74, which is 70, so 74 marks gets A. One call replaces a long chain of if statements, and it stays correct when you add new grade boundaries.
| Method | Returns |
|---|---|
floorKey(k) / ceilingKey(k) | Largest key ≤ k / smallest key ≥ k |
lowerKey(k) / higherKey(k) | Largest key < k / smallest key > k |
firstKey() / lastKey() | Smallest / largest key |
headMap(k) / tailMap(k) | Keys below k / keys from k upwards |
Building an LRU Cache
A cache keeps recently used data in memory. When it is full, a least recently used (LRU) cache throws away the item that has gone unused the longest.
import java.util.*;
public class Main {
// An LRU (least recently used) cache in a few lines
static class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
LruCache(int capacity) {
super(16, 0.75f, true); // true = keep entries in access order
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity; // drop the least recently used entry
}
}
public static void main(String[] args) {
LruCache<String, String> cache = new LruCache<>(3);
cache.put("u1", "Nusrat");
cache.put("u2", "Arif");
cache.put("u3", "Tania");
System.out.println("After 3 puts : " + cache.keySet());
cache.get("u1"); // u1 becomes most recently used
System.out.println("After get u1 : " + cache.keySet());
cache.put("u4", "Imran"); // over capacity: evicts u2
System.out.println("After put u4 : " + cache.keySet());
System.out.println("u2 still cached? " + cache.containsKey("u2"));
cache.put("u3", "Tania M."); // updating also counts as a use
System.out.println("After update : " + cache);
}
}
Output
After 3 puts : [u1, u2, u3]
After get u1 : [u2, u3, u1]
After put u4 : [u3, u1, u4]
u2 still cached? false
After update : {u1=Nusrat, u4=Imran, u3=Tania M.}
- The third constructor argument
trueswitches LinkedHashMap from insertion order to access order: everygetorputmoves that key to the end. - After
get("u1"), the order is u2, u3, u1, so u2 is now the least recently used. removeEldestEntryis called after everyput. Returningtruewhen the size exceeds 3 removes the eldest entry, u2.
Which Map?
| Map | Order | get / put | Use when |
|---|---|---|---|
HashMap | None | O(1) on average | You only need fast lookup |
LinkedHashMap | Insertion or access | O(1) on average | Predictable output order, caches |
TreeMap | Sorted keys | O(log n) | Sorted reports, ranges, nearest key |
Common Mistakes
- Relying on HashMap order in output or tests. It can change between Java versions or as the map grows.
- Using a TreeMap with keys that are not Comparable and no Comparator, which throws
ClassCastException. - Calling
floorEntry(k).getValue()when no key is ≤ k;floorEntryreturnsnull. - Sharing this simple LRU cache between threads. It is not thread-safe.
Practice Exercises
Exercise 1. Using the grades TreeMap, what does grades.ceilingKey(55) return, and what does grades.floorEntry(80).getValue() return?
Show answer
ceilingKey(55) is 60, the smallest key ≥ 55. floorEntry(80) finds key 80 itself, so the value is A+.
Exercise 2. In the LRU cache example, if after the last line you called cache.put("u5", "Mitu"), which key would be removed?
Show answer
The order is u1, u4, u3 (least to most recent), so u1 is evicted, leaving u4, u3, u5.
Frequently Asked Questions
Is there a sorted Set as well?
Yes. TreeSet keeps elements sorted and has the same navigation methods, such as floor and ceiling. LinkedHashSet keeps insertion order.
How do I sort a TreeMap in descending order?
Create it with a reversed comparator, new TreeMap<>(Comparator.reverseOrder()), or use descendingMap() on an existing one to get a reversed view.
Summary
- HashMap: no order. LinkedHashMap: insertion or access order. TreeMap: sorted keys.
- TreeMap’s floor, ceiling, head and tail methods answer “nearest” and “range” questions.
- An access-ordered LinkedHashMap plus
removeEldestEntryis a complete LRU cache. - Choose by what order and lookups you need.
