Interview Q&A / Java

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the difference between HashMap, LinkedHashMap and TreeMap?

SHORT ANSWER

HashMap has no guaranteed order and gives O(1) operations. LinkedHashMap keeps insertion order, also in O(1). TreeMap keeps keys sorted and costs O(log n). Pick by the order you need.

Explain it simply

Three ways to keep contacts: a heap of visiting cards on a table (HashMap, quick to find but no order), a diary where you write contacts as they arrive (LinkedHashMap, remembers arrival order), and an alphabetical address book (TreeMap, always sorted but slower to update).

Example

java
import java.util.*;

Map<String, Integer> hash = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> tree = new TreeMap<>();
for (String k : new String[]{"pune", "agra", "kochi"}) {
    hash.put(k, k.length()); linked.put(k, k.length()); tree.put(k, k.length());
}
System.out.println(linked.keySet());   // prints: [pune, agra, kochi]
System.out.println(tree.keySet());     // prints: [agra, kochi, pune]
// hash.keySet() order is not guaranteed

What to say in the interview

"HashMap uses a hash table, allows one null key, and does not promise any order. LinkedHashMap adds a doubly linked list through the entries to preserve insertion order, or access order, which is handy for an LRU cache. TreeMap uses a red-black tree for sorted keys and navigation methods, with O(log n) cost and no null keys. I default to HashMap and switch only when I need order."

Common mistakes

  • Relying on HashMap's current iteration order. It can change when the map resizes.

#java#collections#map

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.