Java HashMap - 5 Page Quick Guide
1. What is HashMap?
HashMap stores data as Key-Value pairs.
Unique Keys
Duplicate Values Allowed
Average Time Complexity: O(1)
Package: [Link]
Syntax:
HashMap<String,Integer> map = new HashMap<>();
Example
HashMap<String,Integer> marks = new HashMap<>();
[Link]("Alice",90);
[Link]("Bob",80);
[Link](marks);
Important Methods
put(k,v) - Insert or update
get(k) - Return value
remove(k) - Delete entry
containsKey(k) - Check key
containsValue(v) - Check value
size() - Number of pairs
isEmpty() - Check empty
clear() - Remove all
keySet() - All keys
values() - All values
entrySet() - Key-value entries
Example
[Link]([Link]("Alice"));
[Link]([Link]("Bob"));
[Link]("Bob");
Traversal Techniques
Using keySet()
for(String key: [Link]()){
[Link](key+" "+[Link](key));
Using entrySet()
for([Link]<String,Integer> e: [Link]()){
[Link]([Link]()+" -> "+[Link]());
Using values()
for(Integer v: [Link]()) [Link](v);
Internal Working
• HashMap uses hashCode() to calculate a bucket.
• It uses equals() to compare keys.
• If two keys map to the same bucket, a collision occurs.
• Java handles collisions using linked lists/tree bins.
Defaults
Capacity = 16
Load Factor = 0.75
Allows one null key and multiple null values.
Time Complexity
put() = O(1)
get() = O(1)
remove() = O(1)
Worst Case = O(n)
Interview Questions & Practice
Q1. What is the difference between HashMap and Hashtable?
Q2. Why should immutable objects be used as keys?
Q3. Difference between HashMap and LinkedHashMap?
Q4. What is hashCode() and equals()?
Q5. When do we use TreeMap instead of HashMap?
Complete Example
HashMap<Integer,String> map = new HashMap<>();
[Link](1,"Java");
[Link](2,"DSA");
[Link](2,"Spring");
[Link]([Link](1));
for([Link]<Integer,String> e: [Link]()){
[Link]([Link]()+" : "+[Link]());