Java Hashmap: How to get key from value?

前端 未结 30 2262
忘掉有多难
忘掉有多难 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 03:00

    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.

提交回复
热议问题