Stop 08 · Collections & GenericsTopics · 4/10

TreeMap & LinkedHashMap

Part of the Java Roadmap

In short

Sometimes a plain HashMap is not enough. You might need keys sorted, like discount slabs by order value, or you might need to remember the order things were used, like recently viewed products. These two maps cover exactly that.

TreeMap keeps keys sorted and offers range methods like firstKey, floorKey and headMap. LinkedHashMap keeps insertion order and can be set to access order, which makes a simple LRU cache.

The jaadu flips through a thick alphabetised dictionary with one hand while writing names in a long visitor register at a gate desk with the other.

Think of it like this

A dictionary and a visitor register

TreeMap is like a dictionary: words are always in alphabetical order, so you can jump to "the nearest word before this one". LinkedHashMap is like the visitor register at a society gate: entries stay in the order people arrived, and you can even move a regular visitor to the latest line.

Watch it happen

Which ordered map?

TreeMap

  • Keys always sorted (natural order or a Comparator)
  • floorKey, ceilingKey, headMap, tailMap for ranges
  • O(log n) get and put, backed by a red-black tree
  • No null keys

LinkedHashMap

  • Keeps insertion order by default
  • Can switch to access order for LRU caches
  • Nearly as fast as HashMap
  • removeEldestEntry lets you cap the size

Need sorted keys or range lookups? TreeMap. Need predictable order or a small cache? LinkedHashMap.

The big ideas

What you need to know

Sorted keys

TreeMap iterates keys in sorted order and has firstKey() and lastKey() for the ends.

Range questions

floorKey(x) gives the largest key at or below x. Perfect for slabs, grades and tax brackets.

Insertion order

LinkedHashMap remembers the order you put keys in, so printing it gives a stable, predictable result.

LRU cache in a few lines

Pass accessOrder = true and override removeEldestEntry to evict the least recently used entry.

See it in code

Walk through the code

java
1import java.util.LinkedHashMap;2import java.util.Map;3import java.util.TreeMap;4 5public class OrderedMaps {6    public static void main(String[] args) {7        TreeMap<Integer, String> slabs = new TreeMap<>();8        slabs.put(0, "No discount");9        slabs.put(1000, "5% off");10        slabs.put(5000, "10% off");11 12        System.out.println(slabs.floorKey(3200));               // 100013        System.out.println(slabs.floorEntry(7500).getValue());  // 10% off14        System.out.println(slabs.headMap(5000));                // {0=No discount, 1000=5% off}15 16        Map<String, String> recent = new LinkedHashMap<>(16, 0.75f, true) {17            @Override18            protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {19                return size() > 3;20            }21        };22        recent.put("Mumbai", "Rain");23        recent.put("Delhi", "Smog");24        recent.put("Chennai", "Humid");25        recent.get("Mumbai");                  // Mumbai becomes most recent26        recent.put("Kolkata", "Cloudy");       // evicts Delhi27        System.out.println(recent.keySet());   // [Chennai, Mumbai, Kolkata]28    }29}

1/4Slabs are stored by their starting order value, kept sorted automatically.

A TreeMap answering "which discount slab is ₹3,200 in?" and a three-entry LRU cache of recently checked cities.

Save yourself the pain

Common mistakes

Oops

Using TreeMap just to print a map once in sorted order.

Do this instead

Keep the HashMap and sort a copy of the keys when printing. TreeMap is for maps you query by order often.

Oops

Expecting LinkedHashMap to reorder on get() by default.

Do this instead

Only the constructor with accessOrder = true does that. The default keeps insertion order.

Oops

Putting keys in a TreeMap that are not Comparable and passing no Comparator.

Do this instead

Either implement Comparable on the key class or pass a Comparator, or put() throws ClassCastException.

Your mission

Grade lookup and recent searches

~25 min

Quick check

Which TreeMap method returns the greatest key less than or equal to a given key?

Go deeper

  1. 1Print a phone book in alphabetical order using a TreeMap.
  2. 2Use floorKey to find the tax slab for a given income.
  3. 3Build a small LRU cache by extending LinkedHashMap and overriding removeEldestEntry.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge