If I have the value "foo"
, and a HashMap<String> ftw
for which ftw.containsValue("foo")
returns true
, how can I get the corresponding key? Do I have to loop through the hashmap? What is the best way to do that?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
It sounds like the best way is for you to iterate over entries using
map.entrySet()
sincemap.containsValue()
probably does this anyway.My 2 cents. You can get the keys in an array and then loop through the array. This will affect performance of this code block if the map is pretty big , where in you are getting the keys in an array first which might consume some time and then you are looping. Otherwise for smaller maps it should be ok.
In java8
If your data structure has many-to-one mapping between keys and values you should iterate over entries and pick all suitable keys:
In case of one-to-one relationship, you can return the first matched key:
In Java 8:
Also, for Guava users, BiMap may be useful. For example: