Skip to main content
Beginnercomparison

What is the difference between a HashMap and a TreeMap in terms of time complexity and behaviour?

ReportedSource: GeeksforGeeks interview experience: Infosys SP/DSE 2026

Quick answer

HashMap: hash table, O(1) average ops, unordered, one null key. TreeMap: red-black tree, O(log n) ops, sorted keys with range/floor/ceiling queries. LinkedHashMap keeps insertion order.

HashMap.

  • Backed by a hash table (array of buckets).
  • get/put/remove: O(1) average; worst case O(n), improved to O(log n) in Java 8+ because large buckets turn into balanced trees.
  • No ordering of keys. Allows one null key.
  • Needs good hashCode()/equals().

TreeMap.

  • Backed by a red-black tree.
  • get/put/remove: O(log n) guaranteed.
  • Keys kept sorted (natural order or a Comparator); supports range and navigation queries: firstKey, floorKey, ceilingKey, headMap, subMap.
  • No null keys with natural ordering. Needs compareTo/Comparator consistent with equals.

Choosing. Use HashMap for fast lookups when order does not matter; TreeMap when you need sorted iteration or nearest-key queries (e.g. finding the price tier for an amount). LinkedHashMap keeps insertion order (and can act as an LRU cache with accessOrder=true).

Discussion