This week's book giveaway is in the OCP forum.
We're giving away four copies of OCP Java SE 8 Programmer II Exam Study Guide and have Kathy Sierra, Bert Bates, & Elizabeth Robson on-line!
See this thread for details.
Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

HashMap question?  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In HashMap, we can get the value if we know the key:

HashMap hm = new HashMap( );
hm.put("java1","eclipse");
hm.put("java2","NetBean");

String value = (Object)hm.get("java1");

How to get the key if we know the mapping value(object) only?


thanks
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

If you really need to do this, you can call iterator() to get an iteration over Map.Entry objects, and look at the value() in each Map.Entry until you find the value of interest, and then look at the key(). This is obviously quite inefficient if you need to do it multiple times; in that case, consider keeping two maps, one in each "direction."
 
watsonyaya
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can not figure it out, can you show me a sample?

HashMap hm = new HashMap();
hm.put("java1","NetBean");
hm.put("java2","Eclipse");
hm.put("java3","JBuilder");
hm.put("java4","JDeveloper");
Can you retrieve String "java4" if you know the mapping object "Jdeveloper" only?

thanks
 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no easy way to get it (by easy I meant by making a simple method call)

As the values in a hashmap are not distinct, one value may correspond to multiple keys.

You can code a linear search by accessing each elements corresponding to all keys and mark the key(s)
 
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's semi-psuedocode for Ernest's suggestion. It returns the first key that it finds mapped to the given value.Map.Entry is an inner class of Map and contains a single pairing (key and value). Note that some Maps allow null values.
 
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or simply use a BidiMap implementation from http://jakarta.apache.org/commons/collections
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!