pub fn count_values<T>(collection: &[T]) -> HashMap<T, usize>Expand description
Counts the number of occurrences of each value in a collection.
This function iterates over a slice of items and returns a HashMap where each key is a unique
item from the collection, and the corresponding value is the number of times that item appears.
Time Complexity: O(n), where n is the number of elements in the collection.
§Arguments
collection- A slice of items to be counted.
§Type Parameters
T- The type of elements in the input collection. Must implementHash,Eq, andClone.
§Returns
HashMap<T, usize>- A map where keys are unique items from the collection and values are their counts.
§Examples
use lowdash::count_values;
use std::collections::HashMap;
let numbers = vec![1, 2, 2, 3, 4, 3, 5];
let result = count_values(&numbers);
let mut expected = HashMap::new();
expected.insert(1, 1);
expected.insert(2, 2);
expected.insert(3, 2);
expected.insert(4, 1);
expected.insert(5, 1);
assert_eq!(result, expected);use lowdash::count_values;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq, Hash, 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: "Alice".to_string(), age: 25 },
Person { name: "Carol".to_string(), age: 35 },
];
let result = count_values(&people);
let mut expected = HashMap::new();
expected.insert(
Person { name: "Alice".to_string(), age: 25 },
2
);
expected.insert(
Person { name: "Bob".to_string(), age: 30 },
1
);
expected.insert(
Person { name: "Carol".to_string(), age: 35 },
1
);
assert_eq!(result, expected);