20

Possible Duplicate:
Java Hashmap: How to get key from value?
Bi-directional Map in Java?

I want a key value data structure to use for Android App. I can use Map<K,V>, but in Map I can't get key for particular Value.

Is there any good Java data structure using which I can retrieve key by value and vice-versa.

Community
  • 1
  • 1
Sharanabasu Angadi
  • 4,304
  • 8
  • 43
  • 67
  • 7
    Look at Guava's [BiMap](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html) – jlordo Jan 30 '13 at 09:43
  • You could just implement a small method to do so; it will be 4 lines of code; instead of using any third party. – Deepak Singhal Jan 30 '13 at 09:45
  • 4
    @Deepak it is better to use well-tested and widely accepted libraries for such a general use case. You will avoid a lot of pain. – autra Jan 30 '13 at 09:47
  • 1
    Exact duplicate of http://stackoverflow.com/questions/10699492/bi-directional-map-in-java and http://stackoverflow.com/questions/1670038/does-java-have-a-hashmap-with-reverse-lookup – autra Jan 30 '13 at 09:48
  • Second answer on http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value – Deepak Singhal Jan 30 '13 at 09:49

3 Answers3

19

You can use Map with entrySet and Map.Entry class to iterate and get both keys and values even if you don't know any of the keys in the Map.

Map <Integer,String> myMap = new HashMap<Integer,String>();

Iterator<Entry<Integer, String>> iterator = myMap.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<Integer,String> pairs = (Map.Entry<Integer,String>)iterator.next();
    String value =  pairs.getValue();
    Integer key = pairs.getKey();
    System.out.println(key +"--->"+value);
}
Wesley Womack
  • 308
  • 2
  • 11
  • 3
    Sure, this will work. But it will be slower and slower with growing number of entries. He's better of with a `BiMap` – jlordo Jan 30 '13 at 10:07
  • 1
    But He need not to put a new jar file and make his app heavy, And I don't find any much significant change in performance. – Saumik Chaurasia Jan 30 '13 at 10:17
  • 3
    Do you prefer an app that get's slower over time, or an app that is (a tiny little bit) bigger when downloading initially? – jlordo Jan 30 '13 at 10:19
  • 1
    Depends... Also bi map will maintain two maps and internally and not allow me to duplicate value – Saumik Chaurasia Jan 30 '13 at 10:30
  • 1
    which makes total sense: If you had duplicate values, which key would you choose for an inverse lookup?? That's what OP is trying to do. – jlordo Jan 30 '13 at 10:33
1

Use Google Guava BiMap

How to use Guava Libraris in Android is here

Community
  • 1
  • 1
TheWhiteRabbit
  • 15,480
  • 4
  • 33
  • 57
0

The best data structure would be Java HashMaps check this link you can use the get(Object key) method