pub fn key_by<K, V, F>(collection: &[V], iteratee: F) -> HashMap<K, V>Expand description
Creates a HashMap by mapping each element in a collection to a key using an iteratee function.
If multiple elements map to the same key, the last occurrence will overwrite previous ones.
Note: The key type K must implement both Eq and Hash traits to be used in a HashMap.
Time Complexity:
O(n), where n is the number of elements in the collection.
§Arguments
collection- A slice of items from which to create theHashMap.iteratee- A function that takes an item from the collection and returns a key of typeK.
§Type Parameters
K- The type of keys in the resultingHashMap. Must implementEqandHash.V- The type of values in the collection. Must implementClone.F- The type of the iteratee function. Must implementFn(&V) -> K.
§Returns
HashMap<K, V>- AHashMapwhere each key is the result of applying the iteratee to an element in the collection, and each value is the corresponding element from the collection.
§Examples
use lowdash::key_by;
use std::collections::HashMap;
let numbers = vec![1, 2, 3, 4, 5];
let map = key_by(&numbers, |&x| x % 2);
let mut expected = HashMap::new();
expected.insert(1, 5); // Last odd number
expected.insert(0, 4); // Last even number
assert_eq!(map, expected);use lowdash::key_by;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Charlie".to_string(), age: 35 },
];
let map = key_by(&people, |person| person.name.clone());
let mut expected = HashMap::new();
expected.insert("Alice".to_string(), people[0].clone());
expected.insert("Bob".to_string(), people[1].clone());
expected.insert("Charlie".to_string(), people[2].clone());
assert_eq!(map, expected);use lowdash::key_by;
use std::collections::HashMap;
let strings = vec!["apple", "banana", "apricot", "blueberry"];
let map = key_by(&strings, |s| s.chars().next().unwrap());
let mut expected = HashMap::new();
expected.insert('a', "apricot");
expected.insert('b', "blueberry");
assert_eq!(map, expected);