Get count of each value in vector

Viewed 791

I'm searching easy way to count each value in vector in Rust:

let v = vec![1, 2, 2, 1, 3, 2, 3, 5];
let counter: HashMap<_,_> = count_element_function(v);
assert_eq!(counter.get(&1), Some(2));
assert_eq!(counter.get(&2), Some(3));
assert_eq!(counter.get(&3), Some(2));
assert_eq!(counter.get(&5), Some(1));
1 Answers

A simple filter + count does the job if you want to count one item:

fn count<I>(it: I, item: &I::Item) -> usize
where
    I: IntoIterator,
    I::Item: PartialEq,
{
    it.into_iter().filter(|x| x == item).count()
}

fn main() {
    let v = vec![1, 2, 2, 1, 3, 2, 3, 5];
    assert_eq!(count(v, &1), 2);
}

If you want to store all in the hashmap, you can do that:

use std::collections::HashMap;

fn count_element_function<I>(it: I) -> HashMap<I::Item, usize>
where
    I: IntoIterator,
    I::Item: Eq + core::hash::Hash,
{
    let mut result = HashMap::new();

    for item in it {
        *result.entry(item).or_insert(0) += 1;
    }

    result
}

fn main() {
    let v = vec![1, 2, 2, 1, 3, 2, 3, 5];
    let counter: HashMap<_, _> = count_element_function(v);
    assert_eq!(counter.get(&1), Some(&2));
    assert_eq!(counter.get(&2), Some(&3));
    assert_eq!(counter.get(&3), Some(&2));
    assert_eq!(counter.get(&5), Some(&1));
}

I'm not sure that it is the most efficient, though.

Related