Nearby lessons

85 of 125

Java - Map Interface

📌 What You Will Learn
  • What the Collection Framework is and why we need it
  • List, Set, Map and Queue — the four big families
  • Choosing the right collection for the right job
  • Comparable vs Comparator
  • The internal working of HashMap (interview favourite)

Map Interface is a core concept of the Java language. This lesson explains Map — Key-Value Pairs and The Internal Working of HashMap (Interview Favourite) with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Map — Key-Value Pairs

A Map stores pairs: a key and a value. Like a dictionary — you look up a word (key) and get its meaning (value). Keys must be unique; values can repeat.

In simple words: In a Map each key holds exactly one value — putting the same key again overwrites the old value. That is why marks.put("Rahul", 90) quietly replaces Rahul's earlier 88.

HashMap vs LinkedHashMap vs TreeMap vs Hashtable

PointHashMapLinkedHashMapTreeMapHashtable
OrderNo orderInsertion orderSorted by keyNo order
Null key/valueAllowedAllowedKey: noNeither
Thread safe?NoNoNoYes
SpeedFastestMediumSlowerSlow (old)
UseMost commonNeed insertion orderNeed sorted keysLegacy only
Example01
JCode Cell
1import java.util.*;
2 
3class MapDemo {
4 public static void main(String[] args) {
5 Map<String, Integer> marks = new HashMap<>();
6 marks.put("Rahul", 88);
7 marks.put("Priya", 95);
8 marks.put("Anil", 76);
9 marks.put("Rahul", 90); // same key -> value UPDATED to 90
10 
11 System.out.println(marks);
12 System.out.println("Rahul's marks: " + marks.get("Rahul"));
13 System.out.println("Contains Priya? " + marks.containsKey("Priya"));
14 
15 for (Map.Entry<String, Integer> e : marks.entrySet()) {
16 System.out.println(e.getKey() + " -> " + e.getValue());
17 }
18 }
19}
Output
{Rahul=90, Anil=76, Priya=95} Rahul's marks: 90 Contains Priya? true Rahul -> 90 Anil -> 76 Priya -> 95

The Internal Working of HashMap (Interview Favourite)

Every interviewer asks: How does HashMap store data? Here is the simple story:

  • When you call map.put(key, value), Java calculates the hashCode() of the key.
  • That hash value decides which bucket (a box in an array) the entry goes into.
  • If two keys fall in the same bucket (a collision), they are stored in a chain inside that bucket.
  • From Java 8, when a chain becomes long (8+), it is converted into a tree for faster searching.
  • When you call map.get(key), Java computes the same bucket, then finds your key — very fast, almost O(1).
In simple words: HashMap's speed comes from the hash: `put` and `get` jump straight to one bucket instead of scanning everything. If two keys share a bucket they form a small chain — the map still works, only a little slower.
Trainer's Note: Golden rules: 1) If two objects are equal (equals() true), their hashCode() MUST be equal — otherwise HashMap breaks. 2) Override equals() and hashCode() together. 3) Keys should be immutable (like String) so their hash never changes.
Example02
JCode Cell
1put(k, v):
2 index = hash(k) % bucketCount
3 bucket[index] -> chain of entries with same index
4 
5So: equal keys MUST have equal hashCode, so that they land in the same bucket.
📝 Key Takeaways
  • Collection is an interface; Collections is a utility class with static helpers.
  • List = ordered, allows duplicates. Set = no duplicates. Map = key-value pairs. Queue = FIFO.
  • ArrayList is the everyday list; HashMap is the everyday map.
  • HashMap works on hashCode + buckets; collisions chain, then become trees (Java 8+).
  • Comparable (compareTo) is the natural order; Comparator (compare) gives custom order.
  • Always override equals() and hashCode() together for your own objects.
  • Collections.sort() and Collections.reverse() are the handy helpers.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1