Introduction
In Rust, HashMap
is a collection type that stores key-value pairs using a hash table. It allows for efficient insertion, deletion, and lookup operations based on the keys. HashMap
is part of the standard library's std::collections
module and is useful when you need a map with fast access times.
Using HashMap
To use HashMap
, you need to import it from the std::collections
module. You can create a HashMap
by using the HashMap::new
method. Elements can be added using insert
, and accessed or removed using methods like get
and remove
respectively.
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
println!("Map: {:?}", map);
println!("Value for key 'a': {:?}", map.get("a"));
}
// Output:
// Map: {"a": 1, "b": 2}
// Value for key 'a': Some(1)
Key Methods
Below are some of the key methods exposed by the HashMap
class:
HashMap::new
Creates a new, empty HashMap
.
use std::collections::HashMap;
fn main() {
let map: HashMap<&str, i32> = HashMap::new();
println!("Created an empty map: {:?}", map);
}
// Output:
// Created an empty map: {}
HashMap::insert
Adds a key-value pair to the HashMap
. If the key already exists, the corresponding value is updated.
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("key1", 10);
map.insert("key2", 20);
println!("Map after insertions: {:?}", map);
}
// Output:
// Map after insertions: {"key1": 10, "key2": 20}
HashMap::get
Returns a reference to the value corresponding to the key, or None
if the key is not present.
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("key1", 30);
println!("Value for 'key1': {:?}", map.get("key1"));
println!("Value for 'key2': {:?}", map.get("key2"));
}
// Output:
// Value for 'key1': Some(30)
// Value for 'key2': None
HashMap::remove
Removes a key from the HashMap
, returning the value at the key if the key was previously in the map.
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("key1", 40);
println!("Removed value: {:?}", map.remove("key1"));
println!("Map after removal: {:?}", map);
}
// Output:
// Removed value: Some(40)
// Map after removal: {}
HashMap::contains_key
Returns true
if the HashMap
contains a value for the specified key.
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("key1", 50);
println!("Contains 'key1': {}", map.contains_key("key1"));
println!("Contains 'key2': {}", map.contains_key("key2"));
}
// Output:
// Contains 'key1': true
// Contains 'key2': false
Example Usage
Example 1: Basic Usage
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("x", 10);
map.insert("y", 20);
println!("Map: {:?}", map);
println!("Value for key 'x': {:?}", map.get("x"));
}
// Output:
// Map: {"x": 10, "y": 20}
// Value for key 'x': Some(10)
Example 2: Updating a Value
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("key", 1);
map.insert("key", 2);
println!("Map after update: {:?}", map);
}
// Output:
// Map after update: {"key": 2}
Example 3: Removing a Key-Value Pair
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
let removed = map.remove("a");
println!("Removed value: {:?}", removed);
println!("Map after removal: {:?}", map);
}
// Output:
// Removed value: Some(1)
// Map after removal: {"b": 2}
Example 4: Iterating Over Elements
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("c", 3);
map.insert("a", 1);
map.insert("b", 2);
for (key, value) in &map {
println!("Key: {}, Value: {}", key, value);
}
}
// Output:
// Key: c, Value: 3
// Key: a, Value: 1
// Key: b, Value: 2
Example 5: Checking Key Existence
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("k1", 100);
map.insert("k2", 200);
println!("Contains 'k1': {}", map.contains_key("k1"));
println!("Contains 'k3': {}", map.contains_key("k3"));
}
// Output:
// Contains 'k1': true
// Contains 'k3': false
Considerations
HashMap
does not maintain any order of the keys; it is optimized for fast access.- All keys in a
HashMap
must implement theEq
andHash
traits. - For ordered maps, consider using
BTreeMap
instead.
See Also
- BTreeMap - A sorted map useful for maintaining key-value pairs in a sorted order.
- Vec - A growable array type useful for general collection purposes.
- LinkedList - A doubly-linked list useful for fast insertion and deletion at both ends.
- HashSet - An unordered set useful for storing unique values.