How would I be able to get a specific key from its value. Instead of putting in the key and getting the value how would I be able to input a value and get a key?
Asked
Active
Viewed 204 times
1 Answers
2
You cannot do this with a simple Map
(at least not in an efficient manner), because a key can have multiple values and the values have not been stored in a way that makes them quick to retrieve. Using just a regular Map
, you would need to iterate over all the entries to find the corresponding keys for a value. However, you can create your own data structure that includes two maps (one from A to B, and the second from B to A) to create a bidirectional map with a 1:1 mapping, where you can lookup the A from B or B from A in O(1) time (I'm not using "key" and "value", because in a bidirectional map, both types are both). Check out BiMap (HashBiMap source code) from Guava for an example of this.

Michael Aaron Safyan
- 93,612
- 16
- 138
- 200