Java HashMap Class
The Java Collections Framework includes HashMap which belongs to the java.util package. HashMap stores data in key-value pairs where keys are required to be unique while values are permitted to have duplicates. A hash table provides the underlying structure for this collection and enables quick operations for inserting, deleting, and finding elements.
Key Features
- Stores key-value pairs
- Keys must be unique
- The data structure permits a single null key while supporting multiple null values.
- Unordered – does not maintain insertion order
- Non-synchronized (not thread-safe)
Syntax
HashMap<KeyType, ValueType> map = new HashMap<>();
Example
HashMap<Integer, String> students = new HashMap<>();
Example
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> employeeMap = new HashMap<>();
// Adding key-value pairs
employeeMap.put(1, "Alice");
employeeMap.put(2, "Bob");
employeeMap.put(3, "Charlie");
// Access and modify
System.out.println("Employee 2: " + employeeMap.get(2));
employeeMap.put(2, "Bobby");
// Iterating using entrySet
for (Map.Entry<Integer, String> entry : employeeMap.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
// Removing an entry
employeeMap.remove(3);
// Check contents
System.out.println("Has key 1? " + employeeMap.containsKey(1));
System.out.println("Has value 'Charlie'? " + employeeMap.containsValue("Charlie"));
// Clear the map
employeeMap.clear();
System.out.println("Is map empty? " + employeeMap.isEmpty());
}
}
Note
- The hashCode() and equals() methods maintain key uniqueness within this data structure.
- Custom objects that serve as map keys require proper implementation of both hashCode() and equals() methods.
- Use LinkedHashMap for insertion-order retention.
- Use TreeMap for sorted key order.
- Use Collections.synchronizedMap() or ConcurrentHashMap for thread-safe versions.
HashMap vs TreeMap vs LinkedHashMap
| Feature | HashMap | TreeMap | LinkedHashMap |
|---|---|---|---|
| Order | No order | Sorted keys | Insertion order |
| Null Key | Allowed (1) | Not allowed | Allowed (1) |
| Performance | Fastest | Slower | Medium |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com