How do I find the key for a value in a HashMap?

会有一股神秘感。 提交于 2020-12-04 07:59:21

问题


I have a std::collections::HashMap that contains some entries. I want to find the key that corresponds to a particular value that is already in the hash map.


回答1:


Iterate over the entries of the HashMap, find the entry matching the value, and map to the key.

use std::collections::HashMap;

fn find_key_for_value<'a>(map: &'a HashMap<i32, &'static str>, value: &str) -> Option<&'a i32> {
    map.iter()
        .find_map(|(key, &val)| if val == value { Some(key) } else { None })
}

fn main() {
    let mut map = HashMap::new();
    map.insert(1, "a");
    map.insert(2, "b");
    map.insert(3, "c");

    assert_eq!(find_key_for_value(&map, "a"), Some(&1));
    assert_eq!(find_key_for_value(&map, "z"), None);
}

Note that this will only find the first matching value, if you want to find all matching values, you can use filter_map and collect them into a Vec:

use std::collections::HashMap;

fn find_keys_for_value<'a>(map: &'a HashMap<i32, &'static str>, value: &str) -> Vec<&'a i32> {
    map.iter()
        .filter_map(|(key, &val)| if val == value { Some(key) } else { None })
        .collect()
}

fn main() {
    let mut map = HashMap::new();
    map.insert(1, "a");
    map.insert(2, "b");
    map.insert(3, "c");
    map.insert(4, "a");

    let mut keys = find_keys_for_value(&map, "a");
    keys.sort();
    assert_eq!(keys, vec![&1, &4]);
}


来源:https://stackoverflow.com/questions/59401720/how-do-i-find-the-key-for-a-value-in-a-hashmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!