πΊοΈ Java Maps: Your Personal Filing Cabinet
Imagine you have a magical filing cabinet. You write a label on each folder, and inside each folder, you put something special. When you want to find something, you just look at the labelβno need to search through everything!
Thatβs exactly what a Map is in Java. It stores things in key-value pairs. The key is like the label, and the value is whatβs inside the folder.
π§ The Analogy Weβll Use Throughout
Think of a Map like a dictionary. You look up a word (the key), and you find its meaning (the value).
Every Map type we learn is like a special kind of dictionaryβsome are super fast, some keep things in order, some are safe when many people use them at once.
π Map Interface: The Blueprint
Before building any dictionary, we need a plan. The Map interface is that plan. It tells us what every map can do:
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 10); // Add
ages.get("Alice"); // Find β 10
ages.remove("Alice"); // Delete
ages.containsKey("Bob"); // Check β false
What Every Map Can Do
| Method | What It Does |
|---|---|
put(key, value) |
Adds or updates an entry |
get(key) |
Finds the value for a key |
remove(key) |
Deletes an entry |
containsKey(key) |
Checks if key exists |
size() |
Counts entries |
keySet() |
Gets all keys |
values() |
Gets all values |
Key Rule: Each key can appear only once. If you put the same key again, the old value gets replaced!
π HashMap: The Speed Champion
HashMap is the most popular map. Itβs like a magic dictionary that finds any word in almost zero time.
How Does It Work? (Simple Version)
Imagine 16 buckets numbered 0 to 15. When you add a key:
- Java calculates a hash code (a number from the key)
- It picks a bucket:
bucket = hashCode % 16 - It stores your key-value in that bucket
HashMap<String, String> capitals = new HashMap<>();
capitals.put("France", "Paris");
capitals.put("Japan", "Tokyo");
System.out.println(capitals.get("France"));
// β Paris (found instantly!)
Why Is It So Fast?
Finding something doesnβt mean searching every item. You just:
- Calculate the hash code of the key
- Jump directly to the right bucket
- Pick up your value
Itβs like knowing exactly which drawer to open!
graph TD A["Key: &#39;France&#39;"] --> B["Hash Code: 12345"] B --> C["Bucket Index: 5"] C --> D["Value: &#39;Paris&#39;"]
β οΈ Important to Know
- Order is NOT guaranteed. Items may appear in random order.
- Allows ONE null key and multiple null values.
- Not safe for multiple threads using it at the same time.
π HashMap Internal Working: Behind the Curtain
Letβs peek inside the magic box. What really happens?
The Bucket Array
HashMap has an array of buckets. Each bucket can hold a linked list (or a tree for many items).
Buckets: [0] β null
[1] β ("Alice", 25) β null
[2] β ("Bob", 30) β ("Eve", 22) β null
[3] β null
...
What Happens When Two Keys Land in the Same Bucket?
This is called a collision. The solution? Chain them together like train cars!
graph TD B["Bucket 2"] --> N1["#40;Bob, 30#41;"] N1 --> N2["#40;Eve, 22#41;"] N2 --> N3["null"]
Tree Upgrade (Java 8+)
If one bucket gets too crowded (8+ items), Java converts the linked list to a balanced tree. Finding items stays fast even with collisions.
Resizing: When the Map Gets Full
When 75% of buckets are used (the load factor), HashMap doubles its size and rehashes everything.
| Situation | Action |
|---|---|
| < 75% full | Keep adding normally |
| β₯ 75% full | Double buckets, rehash all keys |
This keeps lookups fast!
π LinkedHashMap: Order Keeper
What if you want speed AND you want items to stay in the order you added them?
LinkedHashMap is your answer. It works like HashMap but keeps a double-linked list connecting all entries.
LinkedHashMap<String, Integer> scores = new LinkedHashMap<>();
scores.put("Math", 95);
scores.put("Science", 88);
scores.put("English", 92);
for (String subject : scores.keySet()) {
System.out.println(subject);
}
// Output (in insertion order):
// Math
// Science
// English
How It Remembers Order
Each entry has two extra pointers: before and after. They form a chain in the order you added items.
graph LR A["Math"] --> B["Science"] B --> C["English"]
Access Order Mode
You can also make it remember access order (most recently used last):
LinkedHashMap<String, String> cache =
new LinkedHashMap<>(16, 0.75f, true);
// true = access order mode
This is perfect for building LRU caches (Least Recently Used)!
π³ TreeMap: The Sorted Dictionary
What if you need your dictionary sorted alphabetically (or by some other order)?
TreeMap keeps keys in sorted order automatically!
TreeMap<String, Integer> fruits = new TreeMap<>();
fruits.put("Banana", 3);
fruits.put("Apple", 5);
fruits.put("Cherry", 2);
for (String fruit : fruits.keySet()) {
System.out.println(fruit);
}
// Output (sorted!):
// Apple
// Banana
// Cherry
How Does It Sort?
TreeMap uses a Red-Black Tree (a self-balancing tree). Every time you add something, it finds the right spot to keep everything sorted.
graph TD B["Banana"] --> A["Apple"] B --> C["Cherry"]
Speed Trade-off
| Operation | HashMap | TreeMap |
|---|---|---|
| put/get | O(1) β‘ | O(log n) π³ |
| Sorted iteration | β No | β Yes |
TreeMap is a bit slower, but sorting is automatic!
π§ SortedMap and NavigableMap: Extra Powers
SortedMap Interface
TreeMap implements SortedMap, which adds special methods:
SortedMap<Integer, String> ranks = new TreeMap<>();
ranks.put(1, "Gold");
ranks.put(2, "Silver");
ranks.put(3, "Bronze");
ranks.firstKey(); // β 1
ranks.lastKey(); // β 3
ranks.headMap(2); // β {1=Gold}
ranks.tailMap(2); // β {2=Silver, 3=Bronze}
NavigableMap Interface (Even More Powers!)
NavigableMap extends SortedMap with navigation methods:
NavigableMap<Integer, String> nav = new TreeMap<>();
nav.put(10, "Ten");
nav.put(20, "Twenty");
nav.put(30, "Thirty");
nav.lowerKey(20); // β 10 (strictly less)
nav.floorKey(20); // β 20 (less or equal)
nav.higherKey(20); // β 30 (strictly greater)
nav.ceilingKey(25); // β 30 (greater or equal)
nav.descendingMap(); // β {30=Thirty, 20=Twenty, 10=Ten}
Think of it as a GPS for your mapβyou can go forward, backward, and find nearby keys!
π‘οΈ ConcurrentHashMap: The Team Player
Imagine many people trying to edit the same dictionary at once. Regular HashMap would get confused and break!
ConcurrentHashMap is designed for multi-threaded programs. Many threads can read and write safely.
ConcurrentHashMap<String, Integer> votes =
new ConcurrentHashMap<>();
// Thread 1
votes.put("Pizza", 10);
// Thread 2 (at the same time!)
votes.put("Burger", 8);
// Both work safely!
How It Stays Safe
Instead of locking the whole map, it uses segment-level locking (or in newer Java, bucket-level locking). Different threads can work on different parts at the same time!
graph TD A["Thread 1: Writes to Bucket 3"] --> M["ConcurrentHashMap"] B["Thread 2: Writes to Bucket 7"] --> M C["Thread 3: Reads Bucket 3"] --> M
Key Differences from HashMap
| Feature | HashMap | ConcurrentHashMap |
|---|---|---|
| Thread-safe | β No | β Yes |
| Null keys | β Allowed | β Not allowed |
| Performance (single thread) | Faster | Slightly slower |
| Performance (many threads) | Breaks! | Excellent |
Atomic Operations
ConcurrentHashMap has special methods that do read-modify-write in one step:
// Add 1 to current value (thread-safe!)
votes.compute("Pizza", (k, v) -> v == null ? 1 : v + 1);
// Only put if key is absent
votes.putIfAbsent("Sushi", 5);
π― Quick Summary: Which Map When?
| Need | Use |
|---|---|
| Fastest lookups, order doesnβt matter | HashMap |
| Remember insertion order | LinkedHashMap |
| Keys always sorted | TreeMap |
| Navigate to nearby keys | TreeMap (NavigableMap) |
| Safe with multiple threads | ConcurrentHashMap |
π You Made It!
You now understand the entire Map family in Java:
- β Map Interface β The blueprint for all maps
- β HashMap β The speed champion
- β HashMap Internals β Buckets, hashing, collisions, resizing
- β LinkedHashMap β Keeps insertion order
- β TreeMap β Always sorted
- β SortedMap & NavigableMap β Extra navigation powers
- β ConcurrentHashMap β Safe for multi-threading
Youβre ready to use Maps like a pro! π
Remember: A Map is just a filing cabinet with labels. Pick the right cabinet for your needs, and coding becomes easy!
