Map Interface
Overview
Mapis a key-value pair based data structure.- Each key maps to exactly one value.
- Keys are unique, values can be duplicated.
- Part of
java.utilpackage. - Does NOT extend Collection (important point).
Key Characteristics
| Feature | Description |
|---|---|
| Storage | Key → Value pairs |
| Duplicate Keys | Not allowed |
| Duplicate Values | Allowed |
| Order | Depends on implementation |
| Null Handling | Depends on implementation |
| Thread Safety | Not synchronized (by default) |
Common Implementations
| Implementation | Description |
|---|---|
| HashMap | Unordered, fastest |
| LinkedHashMap | Maintains insertion order |
| TreeMap | Sorted by keys |
| Hashtable | Legacy, synchronized |
Internal Concept
Map<K, V>
Map<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");
Stored as:
1 → A
2 → B
Map-Specific Methods
| Method Signature | Description | Behavior / Edge Case |
|---|---|---|
V put(K key, V value) | Adds or updates entry | Returns old value if key exists |
V get(Object key) | Retrieves value | Returns null if key not found |
V remove(Object key) | Removes mapping | Returns removed value or null |
boolean containsKey(Object key) | Checks key presence | Faster than containsValue |
boolean containsValue(Object value) | Checks value presence | Slower (linear search) |
void putAll(Map<? extends K, ? extends V> m) | Copies all entries | Overwrites duplicates |
void clear() | Removes all entries | Map becomes empty |
View Methods
| Method Signature | Description | Behavior / Edge Case |
|---|---|---|
Set<K> keySet() | Returns all keys | Backed by map |
Collection<V> values() | Returns all values | Can contain duplicates |
Set<Map.Entry<K,V>> entrySet() | Returns key-value pairs | Best for iteration |
Default & Utility Methods (Post Java 8)
| Method Signature | Description | Behavior / Edge Case |
|---|---|---|
V getOrDefault(Object key, V defaultValue) | Returns value or default | No insertion happens |
V putIfAbsent(K key, V value) | Adds only if key absent | Returns existing value if present |
boolean remove(Object key, Object value) | Removes only if match | Prevents accidental removal |
boolean replace(K key, V oldVal, V newVal) | Replaces if match | Returns false if mismatch |
V replace(K key, V value) | Replaces value | Returns old value or null |
void replaceAll(BiFunction<K,V,V> function) | Updates all values | Applies function to each entry |
V compute(K key, BiFunction<K,V,V> remapFn) | Recomputes value | Removes key if result is null |
V computeIfAbsent(K key, Function<K,V> fn) | Adds if absent | Lazy initialization |
V computeIfPresent(K key, BiFunction<K,V,V> fn) | Updates if present | Skips if key missing |
V merge(K key, V value, BiFunction<V,V,V> fn) | Combines values | Removes key if result null |
void forEach(BiConsumer<K,V> action) | Iterates entries | Cleaner than loop |
Code Examples (Important Ones)
1. getOrDefault()
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
System.out.println(map.getOrDefault("A", 0)); // 0
}
2. putIfAbsent()
public static void main(String[] args) {
map.put("A", 10);
map.putIfAbsent("A", 20);
System.out.println(map.get("A")); // 10 (not replaced)
}
3. computeIfAbsent()
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>();
map.computeIfAbsent("A", k -> new ArrayList<>()).add("Apple");
System.out.println(map); // {A=[Apple]}
}
👉 Avoids:
- null checks
- manual initialization
4. computeIfPresent()
public static void main(String[] args) {
map.put("A", 10);
map.computeIfPresent("A", (k, v) -> v + 5);
System.out.println(map.get("A")); // 15
}
Performance (HashMap)
| Operation | Time Complexity |
|---|---|
| Put | O(1) |
| Get | O(1) |
| Remove | O(1) |
| Worst Case | O(n) |
Map vs Collection
| Feature | Collection | Map |
|---|---|---|
| Structure | Single elements | Key-Value pairs |
| Duplicate handling | Depends | Keys unique |
| Interface hierarchy | Root | Separate hierarchy |