A map stores key-value pairs.
Each key is unique, but values can be duplicated.
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
Common Implementation
Implementation | Key Features |
---|---|
HashMap | Fast, no ordering, allows 1 null key |
LinkedHashMap | Maintains insertion order |
TreeMap | Sorted by keys (natural or custom order) |
Hashtable | Legacy, synchronized, no null keys |
ConcurrentHashMap | Thread-safe, no locking entire map |
Methods
map.put("X", 100);
map.get("X"); // 100
map.containsKey("X"); // true
map.containsValue(100); // true
map.remove("X");
map.size();
map.clear();
Iterating over a Map
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
Comparison
HashMap vs TreeMap vs LinkedHashMap
Feature | HashMap | LinkedHashMap | TreeMap |
---|---|---|---|
Order | ✗ None | ✅ Insertion order | ✅ Sorted by key |
Null Keys | ✅ One null key | ✅ One null key | ✗ |
Performance | ✅ Fastest | Slightly slower | Slowest |
Thread-safe | ✗ | ✗ | ✗ |
Key Notes
- Map is not a subtype of Collection.
- Use
equals()
andhashCode()
for key comparison. - For thread-safe use: prefer
ConcurrentHashMap
overHashtable
.
Tip
Be ready to:
- explain how keys are compared,
- compare HashMap vs TreeMap vs LinkedHashMap,
- write code using entrySet() loop,
- mention null-handling rules for keys & values.
Parent: _Collections