10

For example, given the data:

2 : 4  
1 : 3  
5 : 2  

The function would return 2 since its value (4) is the highest.

I am doing:

let mut max_val = 0;
let mut max_key = "";
for (k, v) in a_hash_map.iter() {
    if *v > max_val {
        max_key = k;
        max_val = *v;
    }
}

Is there a nicer or quicker or simpler way to do this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Will
  • 1,059
  • 2
  • 10
  • 22

3 Answers3

22

Iterate through all the key-value pairs in the hashmap, comparing them by the values, keeping only the key of the maximum:

use std::collections::HashMap;

fn example<K, V>(a_hash_map: &HashMap<K, V>) -> Option<&K>
where
    V: Ord,
{
    a_hash_map
        .iter()
        .max_by(|a, b| a.1.cmp(&b.1))
        .map(|(k, _v)| k)
}

fn main() {
    let map: HashMap<_, _> = vec![(2, 4), (1, 3), (5, 2)].into_iter().collect();
    dbg!(example(&map));
}

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
13
let key_with_max_value = a_hashmap.iter().max_by_key(|entry | entry.1).unwrap();

dbg!(key_with_max_value.0);

You will need to do better error handling. This code just does an unwrap, expecting that there would be at least one element.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
apatniv
  • 1,771
  • 10
  • 13
-1

perhaps you can have a try with this: if let Some(max) = a_hash_map.keys().max(){println!("max:{}", max);}

suchjs
  • 29
  • 3
  • This returns the key with the highest value, not the key max associated value. I'll make that more clear in the question. – Will Jun 23 '20 at 01:32