Skip to content

Why TreeMap instead of HashMap?

If HashMap is a sports bike that gets you there fast ⚑, TreeMap is a GPS-guided car that also tells you what’s nearby, what’s next, and how everything is ordered 🌳🧭

You choose TreeMap not for speed, but for ordered intelligence.


πŸ‘‰ Use TreeMap when order and navigation matter more than raw speed


πŸš€ Situations where TreeMap wins

πŸ”Ή 1. You need sorted data

TreeMap<Integer, String> map = new TreeMap<>();
map.

put(3,"C");
map.

put(1,"A");
map.

put(2,"B");

System.out.

println(map);

πŸ‘‰ Output:

{1=A, 2=B, 3=C}

❌ HashMap β†’ random order βœ… TreeMap β†’ always sorted


πŸ”Ή 2. You need range queries

map.subMap(2,5);   // keys between 2 and 5

πŸ‘‰ Real-world:

  • Prices between β‚Ή100–₹500
  • Logs between timestamps

❌ Not possible in HashMap


πŸ”Ή 3. You need nearest values (navigation)

map.ceilingKey(4); // β‰₯ 4
map.

floorKey(4);   // ≀ 4

πŸ‘‰ Real-world:

  • Find closest available slot
  • Next highest bid

πŸ”Ή 4. You need ordered iteration

for(var entry :map.

entrySet()){
        System.out.

println(entry);
}

πŸ‘‰ Always sorted traversal


πŸ”Ή 5. Custom sorting logic

TreeMap<Integer, String> map =
        new TreeMap<>((a, b) -> b - a); // descending

βš–οΈ When NOT to use TreeMap

Use HashMap if:

  • You only need fast lookup
  • Order doesn’t matter
  • No range/nearest queries

πŸ“Š Quick Comparison

Feature TreeMap HashMap
Order Sorted Unordered
Performance O(log n) O(1)
Range queries βœ… ❌
Navigation (floor/ceiling) βœ… ❌

🎯 Real Interview Answer

β€œTreeMap is used instead of HashMap when we need sorted data, range queries, or navigation operations like finding the closest key. While HashMap provides faster access, TreeMap offers ordered storage and additional querying capabilities using a Red-Black tree.”


🧠 Simple Memory Trick

  • HashMap β†’ Fast lookup ⚑
  • TreeMap β†’ Smart lookup 🌳

πŸ’‘ Real-Life Analogy

  • HashMap β†’ dumping files in a drawer
  • TreeMap β†’ neatly sorted files in folders

πŸ‘‰ One is faster πŸ‘‰ The other is usable for complex queries