Java Hashmap: How to get key from value?

前端 未结 30 1883
忘掉有多难
忘掉有多难 2020-11-22 02:14

If I have the value \"foo\", and a HashMap ftw for which ftw.containsValue(\"foo\") returns true, how can I

相关标签:
30条回答
  • 2020-11-22 02:54

    It's important to note that since this question, Apache Collections supports Generic BidiMaps. So a few of the top voted answers are no longer accurate on that point.

    For a Serialized BidiMap that also supports duplicate values ( 1-to-many scenario ) also consider MapDB.org.

    0 讨论(0)
  • 2020-11-22 02:56

    If you build the map in your own code, try putting the key and value in the map together:

    public class KeyValue {
        public Object key;
        public Object value;
        public KeyValue(Object key, Object value) { ... }
    }
    
    map.put(key, new KeyValue(key, value));
    

    Then when you have a value, you also have the key.

    0 讨论(0)
  • 2020-11-22 02:57

    You could insert both the key,value pair and its inverse into your map structure

    map.put("theKey", "theValue");
    map.put("theValue", "theKey");
    

    Using map.get("theValue") will then return "theKey".

    It's a quick and dirty way that I've made constant maps, which will only work for a select few datasets:

    • Contains only 1 to 1 pairs
    • Set of values is disjoint from the set of keys (1->2, 2->3 breaks it)
    0 讨论(0)
  • 2020-11-22 02:59

    If you choose to use the Commons Collections library instead of the standard Java Collections API, you can achieve this with ease.

    The BidiMap interface in the Collections library is a bi-directional map, allowing you to map a key to a value (like normal maps), and also to map a value to a key, thus allowing you to perform lookups in both directions. Obtaining a key for a value is supported by the getKey() method.

    There is a caveat though, bidi maps cannot have multiple values mapped to keys, and hence unless your data set has 1:1 mappings between keys and values, you cannot use bidimaps.

    Update

    If you want to rely on the Java Collections API, you will have to ensure the 1:1 relationship between keys and values at the time of inserting the value into the map. This is easier said than done.

    Once you can ensure that, use the entrySet() method to obtain the set of entries (mappings) in the Map. Once you have obtained the set whose type is Map.Entry, iterate through the entries, comparing the stored value against the expected, and obtain the corresponding key.

    Update #2

    Support for bidi maps with generics can be found in Google Guava and the refactored Commons-Collections libraries (the latter is not an Apache project). Thanks to Esko for pointing out the missing generic support in Apache Commons Collections. Using collections with generics makes more maintainable code.

    0 讨论(0)
  • 2020-11-22 02:59

    I think keySet() may be well to find the keys mapping to the value, and have a better coding style than entrySet().

    Ex:

    Suppose you have a HashMap map, ArrayList res, a value you want to find all the key mapping to , then store keys to the res.

    You can write code below:

        for (int key : map.keySet()) {
            if (map.get(key) == value) {
                res.add(key);
            }
        }
    

    rather than use entrySet() below:

        for (Map.Entry s : map.entrySet()) {
            if ((int)s.getValue() == value) {
                res.add((int)s.getKey());
            }
        }
    

    Hope it helps :)

    0 讨论(0)
  • I think your choices are

    • Use a map implementation built for this, like the BiMap from google collections. Note that the google collections BiMap requires uniqueless of values, as well as keys, but it provides high performance in both directions performance
    • Manually maintain two maps - one for key -> value, and another map for value -> key
    • Iterate through the entrySet() and to find the keys which match the value. This is the slowest method, since it requires iterating through the entire collection, while the other two methods don't require that.
    0 讨论(0)
提交回复
热议问题