Collections Framework
Map Interface
Analyze the Map interface contract, key-value mappings, and collection view operations.
Interview: Focuses on key uniqueness, map collection views (keySet, values, entrySet), and null key/value behaviors.
The java.util.Map interface maps unique keys to values. A Map cannot contain duplicate keys; each key can map to at most one value. It does not extend Collection because its operations are key-value focused.
Unique Keys
Maps require keys to be unique. Inserting a duplicate key replaces the existing value, returning the old value.
Collection Views
Exposes map contents as collections: keySet() (Set), values() (Collection), and entrySet() (Set of Map.Entry).
Map.Entry
The nested Map.Entry<K, V> interface represents a key-value pair, allowing key and value access during iteration.
Collection View Modifications
The collections returned by keySet(), values(), and entrySet() are backed by the Map itself:
- Removing an element from the returned
keySet()orentrySet()removes the corresponding mapping from the underlying Map. - Unsupported Mutation: Calling
add()oraddAll()on these collection views is not supported and throws anUnsupportedOperationException.
Common Pitfalls
- Calling add on keySet(): Trying to add new keys directly using
map.keySet().add(key), which triggers anUnsupportedOperationException. - Modifying map while iterating over entrySet(): Mutating the map's size while traversing its views, raising a
ConcurrentModificationException.
Best Practices
- Iterate via entrySet(): When you need both keys and values, always iterate over
map.entrySet()instead of iterating overkeySet()and callingmap.get(key). This avoids redundant lookup calls. - Use default methods: Use Java 8 default methods like
getOrDefault(key, default),putIfAbsent, andcomputeIfAbsentto write cleaner, safer code.
Interview-Relevant Information
Q1: Why does Map not implement Collection?
Answer: A Map operates on key-value pairs, which requires methods like put(K, V). This is incompatible with the single-element methods defined in the Collection interface, such as add(E).
Q2: What happens if you remove an element from a Map's keySet() view?
Answer: The corresponding key-value pair is removed from the backing Map. The collection views are directly linked to the underlying data structure.
Quick Checklist
Can you explain why Map is a separate root interface, list the three view methods, and describe how removing elements from a view affects the parent map? If yes, you understand Map interface.
Use Cases
Building lookup tables for caching user details by ID.
Counting item frequencies in datasets using merge operations.
Common Mistakes
Iterating keySet and calling map.get(key) on every loop iteration.
Attempting to add elements directly to the keySet view.