03 / 17

What is the difference between HashMap, TreeMap, and LinkedHashMap?

HashMap vs TreeMap vs LinkedHashMap

javascript
  1. 1

    HashMap: expected O(1) get/put; no general sorted iteration guarantee.

  2. 2

    LinkedHashMap: expected O(1) get/put; maintains insertion order, and can also be configured for access order.

  3. 3

    TreeMap: O(log n) get/put/remove; maintains keys in sorted order.

  4. 4

    HashMap is usually preferred for pure key-based lookup.

  5. 5

    TreeMap is appropriate for range queries, sorted traversal, and predecessor/successor operations.

  6. 6

    LinkedHashMap is useful when deterministic iteration order is required.

Difficulty: 4/10

Follow-up Questions

  • How does LinkedHashMap maintain insertion order?
  • When would you choose TreeMap?
  • What are the memory trade-offs?