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 your hashmap contain unique key to unique value mapping, you can maintain one more hashmap that contain mapping from Value to Key. In that case you can use second hashmap to get key.
The simplest way to get the keys from a HashMap in Java is to invoke the keySet() method on your HashMap object. It returns a set containing all the keys from the HashMap .
The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.
Get Keys and Values (Entries) from Java MapThe entrySet() method returns a set of Map. Entry<K, V> objects that reside in the map. You can easily iterate over this set to get the keys and their associated values from a map.
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With