Map Interface In Java
🗺️ What is the Map Interface?
The Map interface in Java is part of the Java Collections Framework, used to store key-value pairs.
🔑 Each key maps to one value only, and keys must be unique.
✅ Key Characteristics:
| Feature | Behavior |
|---|---|
| Key uniqueness | ✅ Keys must be unique |
| Value uniqueness | ❌ Values can be duplicate |
| Null values | ✅ One null key allowed (in HashMap), multiple null values allowed |
| Order | ❌ Not guaranteed (depends on implementation) |
🔧 Common Implementations:
| Implementation | Description |
|---|---|
HashMap |
Unordered, allows one null key |
LinkedHashMap |
Maintains insertion order |
TreeMap |
Sorted by keys (natural or custom order) |
Hashtable |
Thread-safe legacy map (no null key allowed) |
ConcurrentHashMap |
Thread-safe and high performance in concurrency |
🧰 Common Methods in Map Interface:
| Method | Description |
|---|---|
put(K key, V value) |
Inserts or updates key-value pair |
get(Object key) |
Returns the value for the given key |
remove(Object key) |
Removes the key-value pair |
containsKey(Object key) |
Checks if a key exists |
containsValue(Object val) |
Checks if a value exists |
keySet() |
Returns all keys |
values() |
Returns all values |
entrySet() |
Returns key-value pairs as Map.Entry<K,V>
|
🔍 Example:
📦 Summary Table:
| Feature |
Map Interface |
|---|---|
| Stores | Key-Value pairs |
| Allows duplicates | ✅ Values, ❌ Keys |
| Null allowed | ✅ (in HashMap) |
| Common uses | Caching, Dictionaries, Lookup |
🗃️ What is HashMap?
HashMap is a part of Java’s Collections Framework that implements the Map interface.
It stores data as key-value pairs, and keys must be unique.
🔑 Think of it like a dictionary – each word (key) maps to a meaning (value).
⚙️ Internal Working:
-
HashMapuses a hashing mechanism to store and retrieve data. - Internally backed by an array of buckets (each bucket holds entries).
- Each key's
hashCode()determines the bucket index. - If two keys have the same hash, collision occurs and elements are stored using a LinkedList (or Balanced Tree from Java 8 onward).
✅ Features of HashMap:
| Feature | Behavior |
|---|---|
| Key uniqueness | ✅ Yes, only one entry per key |
| Value uniqueness | ❌ No, values can repeat |
| Null keys/values | ✅ One null key, many null values |
| Order | ❌ No guaranteed order |
| Thread-safety | ❌ Not synchronized |
| Performance | ✅ Fast (O(1) average for get/put) |
🧰 Common Methods:
| Method | Description |
|---|---|
put(K key, V value) |
Adds or updates a key-value pair |
get(Object key) |
Retrieves the value for the given key |
remove(Object key) |
Deletes the entry by key |
containsKey(Object k) |
Checks if a key exists |
containsValue(Object v) |
Checks if a value exists |
keySet() |
Returns a set of keys |
values() |
Returns a collection of values |
entrySet() |
Returns a set of key-value pairs |
🔍 Example:
🧠 How HashMap Handles Collisions?
- Calculates
hashCode()of key → gets bucket index. - If index is empty → places the key-value pair.
- If index has existing entries:
- Uses
.equals()to check if the same key exists. - If not same, appends to the bucket (LinkedList/Tree).
- Uses
🚀 Performance:
| Operation | Time Complexity |
|---|---|
put() |
O(1) average |
get() |
O(1) average |
remove() |
O(1) average |
| Worst case: O(n) (e.g., many collisions) |
🔗 What is LinkedHashMap?
LinkedHashMap is a subclass of HashMap that maintains insertion order of key-value pairs.
✅ It combines hash table (like
HashMap) with a doubly linked list to preserve order.
📦 Class Definition:
✅ Key Features:
| Feature | Behavior |
|---|---|
| Order | ✅ Maintains insertion order or access order (if configured) |
| Duplicates | ❌ Keys must be unique |
| Nulls | ✅ Allows one null key and multiple null values |
| Performance | ⚡ Similar to HashMap (O(1) for get/put) with slight overhead |
| Thread Safety | ❌ Not synchronized |
| Underlying Structure | Hash table + Doubly linked list |
🧰 Common Use-Cases:
- Caches (especially with access-ordering)
- When order of insertion matters
- Maintaining predictable iteration order
🧪 Example:
🟢 Output:
🔁 Access-Order (LRU Cache Style)
- Setting
accessOrder = truemakes the map reorder entries based on access (recently used → end). - Useful in LRU (Least Recently Used) cache implementations.
🧠 Summary:
| Feature | HashMap |
LinkedHashMap |
|---|---|---|
| Order | ❌ Unordered | ✅ Maintains order |
| Performance | ⚡ Fast | ⚡ Fast (slightly slower) |
| Nulls | ✅ 1 null key | ✅ 1 null key |
| Use Case | Fast lookup | Ordered maps / caches |
🌲 What is a TreeMap?
A TreeMap is a part of the Java Collections Framework that implements the NavigableMap interface.
It stores key-value pairs in sorted (ascending) order of keys, using a Red-Black Tree internally.
🔑 Unlike
HashMap, the entries inTreeMapare always sorted by key.
✅ Key Features:
| Feature | Behavior |
|---|---|
| Order | ✅ Sorted by keys (natural or custom order) |
| Duplicates | ❌ Keys must be unique |
| Null keys | ❌ Not allowed (throws NullPointerException) |
| Null values | ✅ Allowed |
| Thread-safe | ❌ Not synchronized |
| Performance | 🔁 O(log n) for put(), get(), remove()
|
| Underlying structure | Self-balancing Red-Black Tree |
🔧 Common Methods:
| Method | Description |
|---|---|
put(K key, V value) |
Inserts or updates key-value |
get(K key) |
Retrieves value for given key |
firstKey() |
Returns the lowest key |
lastKey() |
Returns the highest key |
headMap(K key) |
Keys less than given key |
tailMap(K key) |
Keys greater than or equal to given key |
subMap(K from, K to) |
Keys within a specific range |
descendingMap() |
Reverse order view |
🔍 Example:
🟢 Output:
(Entries sorted by keys)
🎯 Custom Sorting with Comparator:
🧠 Summary:
| Feature | HashMap |
LinkedHashMap |
TreeMap |
|---|---|---|---|
| Order | ❌ Unordered | ✅ Insertion | ✅ Sorted by key |
| Null keys allowed? | ✅ One | ✅ One | ❌ Not allowed |
| Time complexity | O(1) avg | O(1) avg | O(log n) |
| Use case | Fast lookup | Ordered output | Sorted key-value data |
🔐 What is ConcurrentHashMap?
ConcurrentHashMap is a thread-safe version of HashMap introduced in Java 1.5.
It allows concurrent access to the map without locking the whole map – making it highly efficient in multithreaded environments.
🔑 Part of
java.util.concurrentpackage.
✅ Key Features:
| Feature | Behavior |
|---|---|
| Thread-safe | ✅ Yes – supports full concurrency for reads & updates |
| Null keys/values | ❌ Not allowed (throws NullPointerException) |
| Performance | ⚡ Faster than Hashtable, avoids global locking |
| Internal structure | Bucket-level locking (uses segments or bins) |
| Lock granularity | Fine-grained (per bucket or segment) |
| Fail-safe iterator | ✅ Iterators don’t throw ConcurrentModificationException
|
🧠 Internal Working (Simplified):
- Internally uses hashing + segmentation + CAS (Compare-And-Swap).
- Instead of locking the entire map, it locks only the specific bucket/bin during a write.
- From Java 8 onwards, it uses synchronized blocks and linked lists / trees instead of segments.
🔍 Example:
🚫 Why No null Allowed?
Because:
-
nullkeys/values can cause ambiguity in concurrent operations likeget(). - To avoid confusion whether the key doesn’t exist or it’s mapped to null.
🔄 Comparison with Other Maps:
| Feature | HashMap |
Hashtable |
ConcurrentHashMap |
|---|---|---|---|
| Thread-safe | ❌ No | ✅ Yes (fully locked) | ✅ Yes (fine-grained lock) |
| Performance | ✅ Fast | ❌ Slower | ✅ Highly efficient |
| Null key/value | ✅ One key, many values | ❌ No | ❌ No |
| Fail-fast iterator | ✅ Yes | ❌ No | ✅ No (fail-safe) |
✅ When to Use ConcurrentHashMap?
- In multi-threaded applications where multiple threads read/write the map.
- For caches, thread-safe registries, or shared data structures.
🧱 What is Hashtable?
Hashtable is a legacy class in Java that implements the Map interface.
It stores key-value pairs and ensures that no duplicate keys are stored.
🔐 It is synchronized, which means it's thread-safe, but slower than
HashMapin single-threaded applications.
✅ Key Features:
| Feature | Behavior |
|---|---|
| Thread-safe | ✅ Yes (methods are synchronized) |
| Null keys/values | ❌ Not allowed (throws NullPointerException) |
| Order | ❌ Unordered |
| Duplicates | ❌ No duplicate keys, ✅ values can be duplicated |
| Legacy | 📦 Introduced in JDK 1.0, before the Collections Framework |
| Performance | 🐢 Slower than HashMap due to synchronized methods |
🧰 Common Methods:
| Method | Description |
|---|---|
put(K key, V value) |
Inserts or updates a key-value pair |
get(Object key) |
Retrieves value for the key |
remove(Object key) |
Removes entry by key |
containsKey(Object k) |
Checks if key exists |
containsValue(Object v) |
Checks if value exists |
isEmpty() |
Checks if map is empty |
size() |
Returns the number of entries |
🔍 Example:
import java.util.Hashtable;
public class HashtableDemo {
public static void main(String[] args) {
Hashtable<String, Integer> table = new Hashtable<>();
table.put("Java", 90);
table.put("Python", 85);
table.put("C++", 88);
System.out.println("Java score: " + table.get("Java"));
for (String key : table.keySet()) {
System.out.println(key + " => " + table.get(key));
}
}
}
🚫 Null Not Allowed
🔄 Comparison with HashMap:
| Feature | HashMap |
Hashtable |
|---|---|---|
| Thread-safe | ❌ No | ✅ Yes |
| Null keys/values | ✅ Allowed | ❌ Not allowed |
| Performance | ✅ Faster | ❌ Slower |
| Fail-fast iterator | ✅ Yes | ❌ No (uses Enumeration) |
| Introduced in | Java 1.2 (modern) | Java 1.0 (legacy) |
🧠 When to Use?
- Avoid in modern applications.
- Use
ConcurrentHashMapfor thread-safe needs, orHashMapwithCollections.synchronizedMap().