rusthashmap

How do I get all keys of a maximum value from a HashMap in Rust?


In Rust, how can I get all keys from a HashMap that have a maximum value?

Say I have something like this:

let words = vec!["Hello", "World", "Hello", "everybody", "in", "the", "World"];
let mut word_count = HashMap::new();

for word in words {
  let count = word_count.entry(word).or_insert(0);
  *count += 1;
}

let max_word = word_count.iter().max_by_key(|entry| entry.1).unwrap().0;
println!("{max_word}");

This only gets me World, but not Hello. How can I get both keys in a Vec?

Related, for a single maximum value: How do I get the key associated with the maximum value of a Rust HashMap?


Solution

  • There are two possible ways: