☕ Java
Intermediate
What is TreeMap in Java?
Answer
A TreeMap is a NavigableMap implementation backed by a red-black tree. It stores key-value pairs in sorted order by key — either natural ordering (if keys implement Comparable) or by a provided Comparator. All basic operations (get, put, remove, containsKey) run in O(log n). TreeMap's unique advantage is its navigation methods: firstKey(), lastKey(), floorKey(k) (largest key ≤ k), ceilingKey(k) (smallest key ≥ k), headMap(k) (view of entries with keys < k), and tailMap(k). Use TreeMap when you need sorted key traversal or range queries; use HashMap when order does not matter and O(1) performance is needed.
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?