Time：2021-6-15

# Explanation content

1. Hash map
(1) The hash map < K, V > type stores a key value K, corresponding to a mapping of value type V. It uses a hash function to map and decide how to put the key and value into memory.
(2) All keys must be of the same type and all values must be of the same type.

2. Create a hash map
(1) Common creation methods

``````use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Red"), 20);
}``````

(2) Create through the collect method of vector

``````use std::collections::HashMap;
let keys = vec![String::from("Blue"), String::from("Yellow")];
let values = vec![10, 20];
let scores: HashMap<_, _> =  keys.iter().zip(values.iter()).collect(); // Note: underline is space occupying``````

``````use std::collections::HashMap;
let ss = HashMap::new();
ss.insert(String::from("Blue"), 10);
ss.insert(String::from("Yellow"), 20);
let key = String::from("Blue");
let value = ss.get(&key); //value = 10``````

4. Traversal

``````let ss = HashMap::new();
ss.insert(String::from("Blue"), 10);
ss.insert(String::from("Yellow"), 20);
//Traversal: will print out each key value pair in any order
for (key, value) in &ss {
println!("{}: {}", key, value);
}``````

5. Update value
(1) Insert value

``````let mut ss = HashMap::new();
ss.insert(String::from("Blue"), 10);
ss.insert(String::from("Blue"), 20);// The value corresponding to the previous blue will be overridden
println!("{:?}",  ss);// Will print {"blue": 20}``````

(2) Insert only when the key value has no corresponding value

``````let mut ss = HashMap::new();
ss.insert(String::from("Blue"), 10);
ss.entry(String::from("Yellow")).or_insert(20);
ss.entry(String::from("Blue")).or_insert(20);
println!("{:?}",  ss);// Will print {"blue": 10} {"yellow": 10}``````

(3) Update a value based on the old value

``````let text = "hello world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!("{:?}", map);``````