A HashMap (also known as a hash table, dictionary, or associative array in different contexts) is a data structure that stores data as a collection of key-value pairs. Each key must be unique, and it is used to calculate an index (or "hash") that determines where the associated value is stored in memory, typically within an underlying array structure often referred to as "buckets" or "bins".
Here's a breakdown of its key characteristics:
Key-Value Pairs: Data is stored in pairs, where a unique key maps to a specific value. Think of it like a real-world dictionary where the word (key) points to its definition (value).
Hashing: It uses a special function called a "hash function" to convert the key into an integer hash code. This hash code is then typically mapped (often using the modulo operator) to an index in the underlying array (bucket).
Efficiency: Because the hash function directly computes the likely location of a value based on its key, basic operations like adding (put), retrieving (get), and removing (remove) elements are very fast on average, typically taking constant time, denoted as O(1).
Unordered (Typically): In many traditional implementations (like older Java versions or standard JavaScript objects), HashMaps do not guarantee any specific order for the key-value pairs. However, some modern implementations (like newer Java HashMaps or Python dictionaries since 3.7) might maintain insertion order.
Collision Handling: It's possible for different keys to produce the same hash code, leading to a "collision" where multiple key-value pairs need to be stored in the same bucket. HashMaps use strategies like "separate chaining" (storing a linked list or tree in each bucket) or "open addressing" (finding the next available slot) to resolve these collisions. Performance can degrade towards O(n) in the worst-case scenario where many keys hash to the same bucket.
Nulls: Many HashMap implementations (like Java's HashMap) allow one null key and multiple null values.
How to Use HashMaps
HashMaps are widely used in programming because they provide fast lookups. Most programming languages have built-in support for them:
Python: Dictionaries (dict) are Python's built-in implementation. {} literal syntax is used.
Java: The java.util.HashMap class is a standard implementation.
JavaScript: Plain Objects ({}) can act as basic hashmaps (string keys only, potential prototype issues), but the Map object (introduced in ES6) is a more robust implementation that allows keys of any type and maintains insertion order.
C++:std::unordered_map (in <unordered_map>) provides a hash table implementation. std::map (in <map>) is an ordered map, typically implemented using a balanced tree, not a hash table.
The general steps to use a HashMap are:
Create/Initialize: Declare and instantiate a new HashMap object.
Add/Update Data: Use a put or set-like method to add new key-value pairs or update the value for an existing key.
Retrieve Data: Use a get-like method with the key to retrieve its associated value.
Remove Data: Use a remove or delete-like method with the key to remove the key-value pair.
Check Existence: Use methods like containsKey or has to check if a key exists before attempting to access it.
Iterate: Loop through the keys, values, or key-value pairs using appropriate methods or loops (e.g., for...in or for...of in JavaScript, enhanced for loops in Java, for loop with .items() in Python).
Common HashMap Operations with Examples
Here are examples in Python, Java, and JavaScript:
Python (dict)
python
# 1. Create a HashMap (dictionary)
student_ages = {"Alice": 21, "Bob": 22}
print(f"Initial map: {student_ages}")
# 2. Add/Update elements (put/set)
student_ages["Charlie"] = 20 # Add new entry
student_ages["Alice"] = 22 # Update existing entry
print(f"After adding/updating: {student_ages}")
# 3. Access elements (get)
bob_age = student_ages["Bob"]
print(f"Bob's age: {bob_age}")
# Safe access using .get() (returns None if key doesn't exist)
david_age = student_ages.get("David")
print(f"David's age (using .get()): {david_age}")
david_age_default = student_ages.get("David", "Unknown") # Provide a default
print(f"David's age (using .get() with default): {david_age_default}")
# 4. Remove elements (remove/delete)
del student_ages["Charlie"]
print(f"After removing Charlie: {student_ages}")
# 5. Check if a key exists
has_alice = "Alice" in student_ages
print(f"Does Alice exist? {has_alice}")
has_charlie = "Charlie" in student_ages
print(f"Does Charlie exist? {has_charlie}")
# 6. Get size
num_students = len(student_ages)
print(f"Number of students: {num_students}")
# 7. Iterate
print("Iterating through students:")
# Iterate through keys
print("Keys:")
for name in student_ages:
print(f" {name}")
# Iterate through values
print("Values:")
for age in student_ages.values():
print(f" {age}")
# Iterate through key-value pairs
print("Items (key-value pairs):")
for name, age in student_ages.items():
print(f" {name}: {age}")
Java (HashMap)
java
import java.util.HashMap;
import java.util.Map; // Import Map interface
public class HashMapExample {
public static void main(String[] args) {
// 1. Create a HashMap
// Use the Map interface type for good practice
Map<String, Integer> studentAges = new HashMap<>();
studentAges.put("Alice", 21);
studentAges.put("Bob", 22);
System.out.println("Initial map: " + studentAges);
// 2. Add/Update elements (put)
studentAges.put("Charlie", 20); // Add new entry
studentAges.put("Alice", 22); // Update existing entry (put replaces)
System.out.println("After adding/updating: " + studentAges);
// 3. Access elements (get)
int bobAge = studentAges.get("Bob");
System.out.println("Bob's age: " + bobAge);
// Safe access (returns null if key doesn't exist)
Integer davidAge = studentAges.get("David");
System.out.println("David's age: " + davidAge);
// Safe access with default value
int davidAgeDefault = studentAges.getOrDefault("David", -1); // Provide a default
System.out.println("David's age (with default): " + davidAgeDefault);
// 4. Remove elements (remove)
studentAges.remove("Charlie");
System.out.println("After removing Charlie: " + studentAges);
// 5. Check if a key exists (containsKey)
boolean hasAlice = studentAges.containsKey("Alice");
System.out.println("Does Alice exist? " + hasAlice);
boolean hasCharlie = studentAges.containsKey("Charlie");
System.out.println("Does Charlie exist? " + hasCharlie);
// Check if a value exists (containsValue)
boolean has22 = studentAges.containsValue(22);
System.out.println("Does age 22 exist? " + has22);
// 6. Get size
int numStudents = studentAges.size();
System.out.println("Number of students: " + numStudents);
// 7. Iterate
System.out.println("Iterating through students:");
// Iterate through keys
System.out.println("Keys:");
for (String name : studentAges.keySet()) {
System.out.println(" " + name);
}
// Iterate through values
System.out.println("Values:");
for (Integer age : studentAges.values()) {
System.out.println(" " + age);
}
// Iterate through key-value pairs (entries)
System.out.println("Entries (key-value pairs):");
for (Map.Entry<String, Integer> entry : studentAges.entrySet()) {
System.out.println(" " + entry.getKey() + ": " + entry.getValue());
}
}
}
JavaScript (Map)
javascript
// 1. Create a HashMap (Map object)
let studentAges = new Map();
studentAges.set("Alice", 21);
studentAges.set("Bob", 22);
console.log("Initial map:", studentAges);
// 2. Add/Update elements (set)
studentAges.set("Charlie", 20); // Add new entry
studentAges.set("Alice", 22); // Update existing entry (set replaces)
console.log("After adding/updating:", studentAges);
// 3. Access elements (get)
let bobAge = studentAges.get("Bob");
console.log("Bob's age:", bobAge);
// Safe access (returns undefined if key doesn't exist)
let davidAge = studentAges.get("David");
console.log("David's age:", davidAge);
// Providing a default requires a check
let davidAgeDefault = studentAges.get("David") !== undefined ? studentAges.get("David") : "Unknown";
console.log("David's age (with default check):", davidAgeDefault);
// 4. Remove elements (delete)
studentAges.delete("Charlie");
console.log("After removing Charlie:", studentAges);
// 5. Check if a key exists (has)
let hasAlice = studentAges.has("Alice");
console.log("Does Alice exist?", hasAlice);
let hasCharlie = studentAges.has("Charlie");
console.log("Does Charlie exist?", hasCharlie);
// 6. Get size
let numStudents = studentAges.size;
console.log("Number of students:", numStudents);
// 7. Iterate
console.log("Iterating through students:");
// Iterate through keys
console.log("Keys:");
for (let name of studentAges.keys()) {
console.log(" " + name);
}
// Iterate through values
console.log("Values:");
for (let age of studentAges.values()) {
console.log(" " + age);
}
// Iterate through key-value pairs (entries) - Default iteration for Map
console.log("Entries (key-value pairs):");
for (let [name, age] of studentAges) { // or studentAges.entries()
console.log(` ${name}: ${age}`);
}
These examples demonstrate the fundamental operations and usage patterns for HashMaps across different popular programming languages. Remember that while the concept is similar, the exact method names and syntax details vary.