Java HashMap - Complete Notes
1. What is HashMap?
HashMap is a class in [Link] that stores key-value pairs. Keys are unique; values can be
duplicated. It is not synchronized and does not maintain insertion order.
2. Declaration
HashMap map = new HashMap<>();
3. Common Methods
put(K,V) - Insert/update
get(K) - Get value
getOrDefault(K,def)
containsKey(K)
containsValue(V)
remove(K)
remove(K,V)
replace(K,V)
replace(K,old,new)
putIfAbsent(K,V)
size()
isEmpty()
clear()
keySet()
values()
entrySet()
forEach()
compute()
computeIfAbsent()
computeIfPresent()
merge()
clone()
equals()
hashCode()
4. Traversal
for(Integer k: [Link]()){}
for(String v: [Link]()){}
for(var e: [Link]()){ [Link](); [Link](); }
5. Internal Working
Uses hashing. A key's hashCode() decides a bucket. equals() resolves key equality. Average
complexity for put/get/remove is O(1). Worst case O(n), improved to O(log n) for heavily-collided
tree bins in modern Java.
6. Null Rules
One null key is allowed. Multiple null values are allowed.
7. Initial Capacity & Load Factor
Default capacity = 16. Default load factor = 0.75. Resize occurs when capacity*loadFactor threshold
is exceeded.
8. Time Complexity
put/get/remove: Average O(1), Worst O(n). containsKey(): Average O(1). Iteration: O(n).
9. HashMap vs LinkedHashMap vs TreeMap
HashMap: No ordering, fastest average.
LinkedHashMap: Maintains insertion order.
TreeMap: Sorted by keys, O(log n).
10. Interview Points
• Keys should be immutable when possible.
• Override hashCode() and equals() for custom key classes.
• HashMap is not thread-safe.
• ConcurrentHashMap is preferred for concurrent access.
• Duplicate keys overwrite old values.
11. Example
HashMap map = new HashMap<>();
[Link]("Alice",90);
[Link]("Bob",85);
[Link]([Link]("Alice"));
for(var e: [Link]()){
[Link]([Link]()+" -> "+[Link]());
}