Skip to content

Rust std::collections::HashMap API

Rust's HashMap<K, V> — a hash map with quadratic probing and SipHash by default.

1 class · 7 methods

HashMap<K, V>

7 methods

A hash map implemented with quadratic probing and SipHash 1-3 (or 2-4) hashing.

HashMap::new() -> HashMap<K, V>

Creates an empty HashMap with the default hasher and capacity.

Returns

HashMap<K, V>

Example

rust
use std::collections::HashMap;
let mut map: HashMap<&str, i32> = HashMap::new();
map.insert("a", 1);
assert_eq!(map.get("a"), Some(&1));
map.insert(k: K, v: V) -> Option<V>

Inserts a key-value pair. If the key already existed, the old value is returned.

Parameters

NameTypeDescription
kKKey to insert.
vVValue to associate with the key.

Returns

Option<V>

Example

rust
use std::collections::HashMap;
let mut map = HashMap::new();
assert_eq!(map.insert("a", 1), None);
assert_eq!(map.insert("a", 2), Some(1));
map.get<Q: ?Sized>(&self, k: &Q) -> Option<&V>

Returns a reference to the value corresponding to the key.

Parameters

NameTypeDescription
k&QKey to look up.

Returns

Option<&V>

Example

rust
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
assert_eq!(map.get("a"), Some(&1));
assert_eq!(map.get("b"), None);
map.remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>

Removes a key from the map, returning the value at the key if the key was previously in the map.

Parameters

NameTypeDescription
k&QKey to remove.

Returns

Option<V>

Example

rust
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
assert_eq!(map.remove("a"), Some(1));
assert_eq!(map.remove("a"), None);
map.len() -> usize

Returns the number of elements in the map.

Returns

usize

Example

rust
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
assert_eq!(map.len(), 2);
map.contains_key<Q: ?Sized>(&self, k: &Q) -> bool

Returns true if the map contains a value for the specified key.

Parameters

NameTypeDescription
k&QKey to check.

Returns

bool

Example

rust
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
assert!(map.contains_key("a"));
assert!(!map.contains_key("b"));
map.iter() -> Iter<K, V>

Returns an iterator visiting all key-value pairs in arbitrary order.

Returns

Iter<K, V>

Example

rust
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
for (k, v) in map.iter() {
    println!("{}: {}", k, v);
}