0

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?

2
  • 1
    Are you using a HashMap? Commented Sep 20, 2015 at 0:09
  • There may be multiple keys for the same value; which would you want? Commented Sep 20, 2015 at 0:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.