简体   繁体   中英

How do I get the key associated with the maximum value of a Rust HashMap?

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?

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM