TreeMap - Returning the Key of a Value
Hi,
I'm having a bit of trouble with manipulating a TreeMap. I am basically using the "containsValue()" method to search my TreeMap for a specific String. Now, once that String has been found, I want to be able to return the Key associated with that Value.
For example:
System.out.println("Enter Search String:");
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
if(myMap.containsValue(br.readLine())){
// Here is where I want the Key to be returned.
}
else
System.out.println("Not Found.");
I've had a look through the API and done some Google searches but I can't seem to find anything that allows me to do this, it would seem like a fairly obvious thing but perhaps I am missing something...?
Thanks.
[1069 byte] By [
DannyGa] at [2007-11-26 22:48:04]

> I'm having a bit of trouble with manipulating a
> TreeMap. I am basically using the "containsValue()"
> method to search my TreeMap for a specific String.
Then my guess is that you should swap the keys and values. Maps
are not especially good in finding the value part of <key, value> pairs.
kind regards,
Jos
JosAHa at 2007-7-10 12:07:29 >

> If I swapped the Key and Value, would I then be able
> to retrieve the Value that corresponds to the Key,
> once I had found the Key?
Yup, that's exactly what Maps are for. Given a key a Map can find the value
associated with that key very fast.
kind regards,
Jos
JosAHa at 2007-7-10 12:07:29 >

Hmm, after having a think about it I am not sure this would work for me, as it would clash with the construction of the rest of my program.
For example, say I have 2 TreeMaps:
Treemap 1
Key Value
1Apple
2Orange
3Banana
Treemap 2
KeyValue
1 Red
2 Orange
3 Yellow
If I searched TreeMap 1 using the "containsValue()" method, for Apple, it would find Apple with the Key "1". Now, I want to use that Key for search TreeMap 2 to find the colour of that Apple. This is fairly easy, because everything would be kept in ascending order from the Key. But I want to be able to delete something from TreeMap 1, and then delete the corresponding item in TreeMap 2. So if I deleted Apple, I want to be able to get the key for Apple, which I can use to delete the equivalent Key in (i.e. Red) in TreeMap 2
...if you follow me....
Thanks.