Java HashMap
HashMap is a class in Java that implements the Map interface.
It stores data as key-value pairs.
Key -> ValueFor example:
101 -> Ashish
102 -> Rahul
103 -> PriyaHashMap belongs to the java.util package.
import java.util.HashMap;Why do we use HashMap?
HashMap is commonly used when we need to:
- Store data using unique keys.
- Quickly retrieve values using keys.
- Add, update, and remove key-value pairs.
- Store data without requiring a particular iteration order.
For example:
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
HashMap<Integer, String> students = new HashMap<>();
students.put(101, "Ashish");
students.put(102, "Rahul");
students.put(103, "Priya");
System.out.println(students.get(102));
}
}Output
RahulCreating a HashMap
HashMap<Integer, String> map = new HashMap<>();A more flexible approach is:
Map<Integer, String> map = new HashMap<>();Here, the reference uses the Map interface while the object is a HashMap.
Adding Elements
Use put().
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C++");Updating a Value
If a key already exists, put() updates its value.
map.put(1, "Java Programming");The previous value associated with key 1 is replaced.
Duplicate Keys
A HashMap does not allow duplicate keys.
map.put(1, "Java");
map.put(1, "Python");The final mapping is:
1 -> PythonThe second put() replaces the first value.
Duplicate Values
Duplicate values are allowed.
map.put(1, "Java");
map.put(2, "Java");This is valid.
1 -> Java
2 -> JavaRetrieving a Value
Use get().
String value = map.get(1);
System.out.println(value);Output
JavaNull Keys and Values
HashMap permits:
- One null key.
- Multiple null values.
Example
HashMap<Integer, String> map = new HashMap<>();
map.put(null, "Unknown");
map.put(1, null);
map.put(2, null);This is valid for HashMap.
HashMap Does Not Guarantee Order
HashMap does not guarantee insertion order or sorted order.
For example:
HashMap<Integer, String> map = new HashMap<>();
map.put(3, "C");
map.put(1, "A");
map.put(2, "B");
System.out.println(map);The displayed order should not be relied upon.
If insertion order is important, consider LinkedHashMap.
If sorted key order is required, consider TreeMap.
Iterating Through HashMap
Using entrySet()
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(
entry.getKey() + " -> " + entry.getValue()
);
}Using keySet()
for (Integer key : map.keySet()) {
System.out.println(key);
}Using values()
for (String value : map.values()) {
System.out.println(value);
}Important HashMap Methods
| Method | Purpose |
|---|---|
| put() | Adds or updates an entry |
| get() | Retrieves a value |
| remove() | Removes an entry |
| containsKey() | Checks for a key |
| containsValue() | Checks for a value |
| size() | Returns number of entries |
| isEmpty() | Checks whether map is empty |
| clear() | Removes all entries |
| keySet() | Returns keys |
| values() | Returns values |
| entrySet() | Returns entries |
| getOrDefault() | Gets value or default |
| putIfAbsent() | Adds when the key is absent or mapped to null |
Example: Employee Information
HashMap<Integer, String> employees = new HashMap<>();
employees.put(101, "Ashish");
employees.put(102, "Rahul");
employees.put(103, "Priya");
System.out.println(employees.get(101));Output
AshishExample: Counting Occurrences
A HashMap can also be used to count how many times an item appears.
String[] languages = {
"Java", "Python", "Java", "C++", "Java"
};
HashMap<String, Integer> count = new HashMap<>();
for (String language : languages) {
count.put(
language,
count.getOrDefault(language, 0) + 1
);
}
System.out.println(count);The map stores the frequency of each language.
Conceptually:
Java -> 3
Python -> 1
C++ -> 1HashMap Performance
For typical use cases, HashMap provides average constant-time performance for basic operations such as:
- put()
- get()
- remove()
- containsKey()
The exact performance can depend on hashing, collisions, and the internal structure.
HashMap vs LinkedHashMap
| HashMap | LinkedHashMap |
|---|---|
| No guaranteed iteration order | Maintains insertion order by default |
| General-purpose Map | Useful when predictable iteration order is needed |
| Usually slightly less overhead | Maintains additional links between entries |
| Allows one null key | Allows one null key |
HashMap vs TreeMap
| HashMap | TreeMap |
|---|---|
| No guaranteed sorted order | Keys are sorted |
| Average O(1) basic lookup/update | O(log n) basic operations |
| Usually used for fast key-based access | Used when sorted/navigable keys are required |
| Allows one null key | Natural ordering generally does not permit null keys |
Is HashMap Thread-Safe?
HashMap is not synchronized.
If multiple threads modify the same map concurrently, appropriate synchronization or a concurrent collection such as ConcurrentHashMap may be needed.
Important Points
- HashMap implements Map.
- It stores key-value pairs.
- Keys are unique.
- Duplicate values are allowed.
One null key is allowed. Multiple null values are allowed. It does not guarantee insertion or sorted order. It is not synchronized. It is commonly used for fast key-based lookup.
Key Takeaway
Use HashMap when you need a general-purpose key-value data structure and do not need a guaranteed iteration order.
Map<Integer, String> map = new HashMap<>();See you in next page....🙂