HashMap<K, V>
7 methodsA 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
| Name | Type | Description |
|---|---|---|
| k | K | Key to insert. |
| v | V | Value 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
| Name | Type | Description |
|---|---|---|
| k | &Q | Key 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
| Name | Type | Description |
|---|---|---|
| k | &Q | Key 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() -> usizeReturns 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) -> boolReturns true if the map contains a value for the specified key.
Parameters
| Name | Type | Description |
|---|---|---|
| k | &Q | Key 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);
}