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.
-
If you need lookups by both key and value, and the values are unique, you can also use a bijective map implementation, e.g. the one provided by the bimap crate.– Sven MarnachDec 19, 2019 at 14:13
Add a comment
|
1 Answer
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]);
}
-
3"and collect them into a Vec" better to return an
impl Iterator<Item=i32> + 'a
and let the user collect if necessary. Also, funny I didn't knowfind_map()
exist Dec 19, 2019 at 1:35