Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

hashmap

rust

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.

like image 836
euclio Avatar asked Dec 19 '19 00:12

euclio


People also ask

Can we get key from value in HashMap?

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.

How do you get the key of a HashMap?

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 .

Can we get key from value in Hashtable?

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.

How do you get a key value pair on a map?

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.


1 Answers

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]);
}
like image 114
euclio Avatar answered Oct 01 '22 01:10

euclio