Map in Java
The Map interface defines a key-value store with no duplicate keys, serving as the foundation for HashMap, TreeMap, and LinkedHashMap.
Map<K, V> is a core interface in the Java Collections Framework that associates unique keys with values. Unlike Collection, Map does not extend it — a map is a separate hierarchy. Every key is unique; adding a new value for an existing key replaces the old value. Understanding the Map interface gives you a blueprint for all map implementations: HashMap, LinkedHashMap, TreeMap, Hashtable, and ConcurrentHashMap.
The Map Interface Hierarchy
Map<K,V>
├── HashMap<K,V> (hash table, O(1) avg, unordered)
├── LinkedHashMap<K,V> (hash table + linked list, insertion/access order)
├── Hashtable<K,V> (legacy, fully synchronized)
├── TreeMap<K,V> (red-black tree, sorted keys, O(log n))
└── ConcurrentHashMap<K,V>(thread-safe, no null keys/values)
SortedMap<K,V> extends Map<K,V>
└── NavigableMap<K,V> extends SortedMap<K,V>
└── TreeMap<K,V>
Core API
| Method | Description |
|---|---|
put(K, V) |
Associates key with value; returns old value or null |
get(Object key) |
Returns value for key, or null if absent |
getOrDefault(K, V default) |
Returns value, or default if key absent |
containsKey(Object key) |
Returns true if key exists |
containsValue(Object value) |
Returns true if value exists (O(n)) |
remove(Object key) |
Removes entry; returns removed value or null |
putIfAbsent(K, V) |
Puts only if key is absent |
computeIfAbsent(K, Function) |
Computes and puts value only if key absent |
computeIfPresent(K, BiFunction) |
Updates value only if key present |
merge(K, V, BiFunction) |
Merges value with existing using function |
forEach(BiConsumer) |
Iterates all entries |
keySet() |
Returns Set view of keys |
values() |
Returns Collection view of values |
entrySet() |
Returns Set<Map.Entry<K,V>> view of entries |
Examples
Common Map operations
import java.util.HashMap;
import java.util.Map;
public class MapBasics {
public static void main(String[] args) {
Map<String, Integer> wordCount = new HashMap<>();
// put and get
wordCount.put("hello", 1);
wordCount.put("world", 2);
System.out.println(wordCount.get("hello")); // 1
System.out.println(wordCount.get("missing")); // null
// getOrDefault avoids null checks
System.out.println(wordCount.getOrDefault("missing", 0)); // 0
// putIfAbsent — only inserts if key is absent
wordCount.putIfAbsent("hello", 99); // ignored, "hello" already exists
System.out.println(wordCount.get("hello")); // still 1
// Replacing a value
wordCount.put("hello", wordCount.get("hello") + 1);
// Or more idiomatically:
wordCount.merge("hello", 1, Integer::sum); // hello -> 3
// Iterating entries
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
}
Using computeIfAbsent for grouping
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GroupingExample {
public static void main(String[] args) {
List<String> words = List.of("apple", "ant", "banana", "bat", "cherry");
// Group words by first letter
Map<Character, List<String>> groups = new HashMap<>();
for (String word : words) {
char key = word.charAt(0);
// computeIfAbsent creates the list only the first time
groups.computeIfAbsent(key, k -> new ArrayList<>()).add(word);
}
groups.forEach((k, v) -> System.out.println(k + " -> " + v));
// a -> [apple, ant]
// b -> [banana, bat]
// c -> [cherry]
}
}
Common Mistakes
-
Using
getreturn value without a null check.getreturnsnullfor absent keys. Calling methods on the returned value without a null check causesNullPointerException. PrefergetOrDefaultorcontainsKeybeforeget. -
Compound check-then-act. A pattern like
if (!map.containsKey(k)) map.put(k, ...)is not atomic and fails under concurrency. Even in single-threaded code, it is cleaner to useputIfAbsentorcomputeIfAbsent, which are single-call operations. -
Iterating and modifying concurrently. Modifying a
HashMapduring a for-each over itsentrySet()throwsConcurrentModificationException. Use anIteratorexplicitly withiterator.remove(), or build a list of changes and apply them after iteration. -
Confusing
remove(Object key)withremove(Object key, Object value). The two-argumentremoveremoves the entry only if the key is mapped to the specified value (conditional remove). Passing the wrong overload can silently do nothing. -
Using mutable objects as keys. If a key's
hashCodeorequalschanges after insertion (because it is mutable), the entry becomes unreachable —getreturnsnulleven though the key is in the map. Always use immutable objects as map keys.
Best Practices
- Program to the
Map<K, V>interface, not toHashMaporTreeMapdirectly. - Use
computeIfAbsentfor lazy initialisation of values (e.g., grouping into lists or sets). - Use
mergefor accumulating values (e.g., word frequency counting) instead ofget-then-put. - Use
Map.of(...)andMap.copyOf(...)(Java 9+) for small, immutable maps. - When iterating, prefer
entrySet()over separatekeySet()+get(key)calls to avoid the extra lookup.
Interview Questions
1. What is the Map interface and how does it differ from Collection?
Map<K, V> stores key-value pairs where each key is unique. It does not extend Collection because maps are semantically different from single-element collections — they store pairs, not individual elements. Collection has methods like add(E) which do not apply to the pair-based model of Map.
2. What is the difference between Map.Entry and entrySet?
entrySet() returns a Set<Map.Entry<K, V>> — a live view of all key-value pairs in the map. Each Map.Entry is a key-value pair object with getKey() and getValue() methods. Iterating entrySet() is the most efficient way to visit all entries because it avoids a second get call for each key.
3. What happens when you put a duplicate key?
put(key, newValue) replaces the existing value and returns the old value. The key count stays the same. This is why Map guarantees at most one value per key.
4. What is computeIfAbsent and when should you use it?
computeIfAbsent(key, mappingFunction) checks if the key is absent; if so, it calls the function to compute a value and inserts the result, then returns it. If the key is already present, it returns the existing value without calling the function. It is ideal for lazy initialisation — for example, map.computeIfAbsent(key, k -> new ArrayList<>()).add(item).
5. What is the difference between putIfAbsent and computeIfAbsent?
putIfAbsent(key, value) always evaluates the value argument (since Java evaluates arguments before method calls). computeIfAbsent(key, fn) only calls the function if the key is absent, which is important when value creation is expensive or has side effects.
6. What is the merge method used for?
merge(key, value, remappingFunction) inserts value if the key is absent, or applies the function to the existing value and the new value if the key is present. It is ideal for accumulating values: map.merge(word, 1, Integer::sum) increments a word count in one call.
7. How are keySet, values, and entrySet views related to the map?
All three return live, backed views. Changes to the map are reflected in the view, and structural changes through the view (e.g., keySet().remove(k)) are reflected in the map. They are not independent copies. Iterating while modifying through the view throws ConcurrentModificationException.
Summary
Map<K, V>stores unique-key–to-value associations and is the root interface for all Java map implementations.- Core utility methods include
getOrDefault,putIfAbsent,computeIfAbsent,merge, andforEach. - Never use mutable objects as keys — if the hash or equality changes, entries become unreachable.
- Use
entrySet()iteration rather thankeySet()+getfor efficiency. - Choose the right implementation:
HashMapfor speed,LinkedHashMapfor ordered iteration,TreeMapfor sorted keys,ConcurrentHashMapfor concurrency.
Continue Learning
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.