Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Collections Deep Dive — List, Set, Map, Queue

When would you choose a TreeMap or LinkedHashMap over a plain HashMap?

Level II · JuniorCollections Deep Dive — List, Set, Map, Queue
Short answer

Use HashMap as the default for O(1) average access with no ordering guarantees.

Explanation

Use LinkedHashMap when you need predictable iteration order — insertion order, or access order for building an LRU cache via removeEldestEntry. Use TreeMap when you need sorted keys or range queries (the NavigableMap operations: floorKey, ceilingKey, subMap, headMap), accepting O(log n) operations and a Comparable key or supplied Comparator. The choice is driven entirely by the ordering and navigation guarantees you need versus raw speed.

Common mistakes
  • Using TreeMap when no ordering is needed, paying O(log n).
  • Not knowing LinkedHashMap can be an LRU cache with accessOrder.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Collections Deep Dive — List, Set, Map, Queue.

Practise free

More on Collections Deep Dive — List, Set, Map, Queue