问题
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