HashMap vs TreeMap vs LinkedHashMap (and ConcurrentHashMap)
35 min · Intermediate
Java's main maps differ in three ways: the order of keys, the speed of lookups and the null rules. HashMap has no order, LinkedHashMap remembers insertion or access order, TreeMap keeps keys sorted, and ConcurrentHashMap is safe across threads.
Topics in this lesson
- Ordering, complexity and null rules side by side
- LinkedHashMap access order and an LRU cache
- TreeMap navigation: floorKey, ceilingKey, headMap
- HashMap vs Hashtable vs ConcurrentHashMap in one minute
- Choosing the right map
Interview questions this lesson answers
- What is the difference between HashMap, LinkedHashMap and TreeMap?
- How would you implement an LRU cache in Java?
- Can a TreeMap have a null key?
- Why is Hashtable considered legacy?
- How is ConcurrentHashMap thread-safe without locking the whole map?
- Why does ConcurrentHashMap not allow null values?
- Which map would you use to find the nearest lower price for a given amount?
- What does the Map interface guarantee about order?
- How does LinkedHashMap remember order?
- Is LinkedHashMap slower than HashMap?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.