Reading history

Java TreeMap, LinkedHashMap and an LRU Cache

6 min read 0 views

Compare HashMap, LinkedHashMap and TreeMap, use TreeMap navigation methods like floorEntry, and build an LRU cache with LinkedHashMap in Java.

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.
  • LinkedHashMap remembers insertion order: Sylhet first, as it was added first.
  • TreeMap keeps keys sorted: Barishal, Dhaka, Khulna, and so on.
  • All three hold the same entries; equals compares 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.

MethodReturns
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.

least recentmost recentput u1, u2, u3u1u2u3get u1u2u3u1put u4 (full)u3u1u4u2 evictedput u3 (update)u1u4u3capacity 3: the leftmost key is removed when a 4th is added
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 true switches LinkedHashMap from insertion order to access order: every get or put moves that key to the end.
  • After get("u1"), the order is u2, u3, u1, so u2 is now the least recently used.
  • removeEldestEntry is called after every put. Returning true when the size exceeds 3 removes the eldest entry, u2.

Which Map?

MapOrderget / putUse when
HashMapNoneO(1) on averageYou only need fast lookup
LinkedHashMapInsertion or accessO(1) on averagePredictable output order, caches
TreeMapSorted keysO(log n)Sorted reports, ranges, nearest key

Common Mistakes

  1. Relying on HashMap order in output or tests. It can change between Java versions or as the map grows.
  2. Using a TreeMap with keys that are not Comparable and no Comparator, which throws ClassCastException.
  3. Calling floorEntry(k).getValue() when no key is ≤ k; floorEntry returns null.
  4. 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 removeEldestEntry is a complete LRU cache.
  • Choose by what order and lookups you need.

Next: Java ExecutorService and Thread Pools.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *