# Hash Maps Instead of using an index, you use a key generated by a function This key can be anything you want, but it then generates an "index" based on the key which will access a specific value. ## New Hash Map ```rust use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); // Form 2 - Join 2 vectors of different types let teams = vec![String::from("Blue"), String::from("Yellow")]; let initial_scores = vec![10, 50]; let mut scores: HashMap<_, _> = teams.into_iter().zip(initial_scores.into_iter()).collect(); ``` `<_ , _>` infers the typoe from the collect operation `.zip` joins into a tuple the iterator passed into it. `collect()` which turns it into an item for a hash map. ## Ownership in Hash Maps `Copy` types are copied, `Move` types are moved, Hash Map always gets ownership. If you use a hash map of references, then the items which are referenced must be valid for as logn as the HashMap is valid too. ## Accessing values in HashMap `hashmap.get(&key_var)` returns an `Option` We can also iterate using a tuple of variabels to get them ```rust for(key, value) in &hashmap { println!("{}:{}", key, value); } ``` ## Updating a Hashmap ```rust // just insert into the same key scores.insert(String::from("Blue"), 10); scores.insert(String::from("Blue"), 20); // Insert if it does not exist scores.entry(String::form("Blue")).or_insert(50); // Entry returns another Option, if the entry exists it will not execute as the value already is set, else it will return mutable reference to an empty value to be filled ``` ### Updating based on old value ```rust use std::collections::HashMap; 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); //If the word was not in the map, the entry is created and set to 0 // Count becomes the reference to the value keeping count fo words *count += 1; // We dereference and +1 the count of that word (value in keymap). } println!("{:?}", map); ``` ## Hashing Functions The default function is called `SipHash` which is not the fastest but a quite secure system. That can be changed specifying a `BuildHasher` train in another function/struct/... (Chapter 10), be it by yourself or from a crate