Java Hashmap: How to get key from value?

前端 未结 30 2368
忘掉有多难
忘掉有多难 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: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)

提交回复
热议问题