Intermediate · The collections framework · topic 33 of 60 · 30 min
Maps: HashMap, LinkedHashMap and TreeMap
Explanation
Why maps?
Looking things up by a key is everywhere: the stock of a SKU, the city for a PIN code, the cart of a user id. Searching a list each time is slow. A Map stores pairs and finds the value for a key almost instantly.
Map<String, Integer> stock = new HashMap<>();
stock.put("RICE-5KG", 40);
stock.put("DAL-1KG", 25);
stock.put("RICE-5KG", 38); // same key: value replaced
System.out.println(stock.get("RICE-5KG")); // 38
System.out.println(stock.get("GHEE")); // null (no such key)
System.out.println(stock.getOrDefault("GHEE", 0)); // 0
System.out.println(stock.containsKey("DAL-1KG")); // true
stock.remove("DAL-1KG");
for (Map.Entry<String, Integer> e : stock.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}Counting and grouping, the modern way
String[] words = {"chai", "samosa", "chai", "jalebi", "chai"};
Map<String, Integer> count = new HashMap<>();
for (String w : words) count.merge(w, 1, Integer::sum); // {chai=3, samosa=1, jalebi=1}
Map<String, List<String>> byCity = new HashMap<>();
byCity.computeIfAbsent("Pune", k -> new ArrayList<>()).add("Asha");
byCity.computeIfAbsent("Pune", k -> new ArrayList<>()).add("Ravi");
System.out.println(byCity); // {Pune=[Asha, Ravi]}Which Map?
| Map | Key order | Speed | Notes |
|---|---|---|---|
| HashMap | No guaranteed order | O(1) average | Allows one null key; the default choice |
| LinkedHashMap | Insertion order (or access order) | O(1) average | Good for predictable output; can build an LRU cache |
| TreeMap | Sorted keys | O(log n) | firstKey, floorKey, headMap, tailMap |
| Map.of(...) | Unspecified | - | Small unmodifiable maps (Java 9+) |
How HashMap works (interview favourite)
- Inside is an array of buckets.
- put(key, value) calls key.hashCode(), mixes the bits, and picks a bucket index from it.
- If the bucket is empty, the entry goes there. If other keys are already there (a collision), Java compares with equals: an equal key gets its value replaced; otherwise the new entry is added to that bucket.
- When the map gets too full (by default more than 75% of the buckets, the load factor 0.75), it doubles its array and redistributes the entries (rehashing).
- Since Java 8, a bucket with many colliding entries is turned into a small balanced tree, so the worst case stays fast.
get(key) repeats the same steps to find the bucket and uses equals to find the exact key. That is why keys must have correct, consistent equals and hashCode, and why mutable objects make poor keys.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Maps: HashMap, LinkedHashMap and TreeMap · 1/6
In this lesson you will look things up by key with Maps.
Prefer a video by a teacher? Find free videos on “java hashmap internal working buckets hashcode equals tutorial” on YouTube ↗
In real life: Sales per city
An analytics job at a retail chain reads thousands of sales records and totals the amount per city with merge. A TreeMap is used for the final report so cities print alphabetically.
record Sale(String city, int amount) {}
List<Sale> sales = List.of(new Sale("Pune", 500), new Sale("Agra", 300), new Sale("Pune", 200));
Map<String, Integer> totals = new TreeMap<>();
for (Sale s : sales) totals.merge(s.city(), s.amount(), Integer::sum);
System.out.println(totals); // {Agra=300, Pune=700}Practice (0/3 done)
What does this print? Map<String, Integer> m = new HashMap<>(); m.put("a", 1); m.put("a", 2); m.merge("a", 10, Integer::sum); System.out.println(m.get("a") + " " + m.size());
The same counting idea in JavaScript, which runs here: write wordCount(text) that returns a Map from each lower-case word to its count, like Java's map.merge(word, 1, Integer::sum).
Write a program that groups students by city: from a list of records Student(name, city), build a Map<String, List<String>> with computeIfAbsent, then print the cities in alphabetical order with a TreeMap, each followed by its students.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Sorting with Comparable and ComparatorThe collections framework · same module
- Collections overview and ListThe collections framework · same module
- HashMap and HashSetRust Programming · Error handling and collections
- std::map and std::unordered_mapC++ Programming (modern C++ and DSA) · The Standard Template Library (STL)
- Java interview questionsDesign patterns, JVM internals and interviews
- Maps: key-value look-upsGo Programming (backend and cloud) · Collections and structs
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What does map.get(key) return for a missing key in a HashMap?
Answer: null
Use getOrDefault to avoid null.
Which map keeps keys sorted?
Answer: TreeMap
TreeMap is sorted by key.
What is the default load factor of HashMap?
Answer: 0.75
At 75% full the table is resized.
Which two methods must a HashMap key class implement correctly?
Answer: equals and hashCode
hashCode chooses the bucket; equals finds the key.
Which key type cannot be used in a std HashMap?Related
Answer: f64
f64 does not implement Hash and Eq, because NaN is not equal to itself.
From HashMap and HashSet
Default Object.equals behaves like…Related
Answer: ==, same object only
Without overriding, equals checks identity.
What is the time to find a key in std::map with n keys?Related
Answer: O(log n)
std::map is a balanced tree, so its height is about log n.
Why must a HashMap key override both equals and hashCode?Related
Answer: So equal keys land in the same bucket and are found
The contract keeps lookups correct.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “The collections framework” before its exam: Sorting with Comparable and Comparator, Queues, stacks and priority queues.
- Module 7 exam: The collections framework · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Lambdas, streams and files. 60 topics left in the course before the final exam.