Hi,
Consider:
Key Value
0001_A car
0002_B bike
0003_C bus
...
I want to get the key that maps car. All i know is that "_A" is part of the key.
Is it possible to get a key from a LinkedHashMap when you only know part of the key?
Cheers
ST
Patricia Shanahan - 14 Apr 2006 02:56 GMT
> Hi,
>
[quoted text clipped - 11 lines]
> Cheers
> ST
You can get anything from any Map, slowly, by iterating through the
entrySet result checking your criteria.
If you will only have one key with value "car" and need to do this
lookup frequently, consider using a pair of maps. The second map would
have the vehicle names as keys, and the codes as values.
You cannot benefit from the hash lookup without using a key that has the
right hash code and compares equal to the key in the Map.
Patricia
ducnbyu@aol.com - 15 Apr 2006 02:45 GMT
What she said.
Also, specifically a hash map is only useful for exact match on the
key. If there are specific access patterns like your example where you
know the user will do suffix searches you can do like Patricia said and
have a second map.
Or you could reverse the order of your key such as A_0001 and use a
TreeMap and use the subMap() or tailMap() methods for partial key
access. Use get() to get on the whole key. But then you will lose the
ability to efficiently get partial key "0001" if you reverse the key.
TreeMap just gives you efficient access with partial keys starting from
the front of the key. If your key values allow, you could insert both
forward and backward versions of your key into a TreeMap linking to the
same result object (0001_A, car) and (A_0001, car), but that is hardly
better than two TreeMaps really.
If you are looking for an individual index scheme that gives you direct
access to an arbitrary substring of your key there is no such magic as
yet.
You could also extend the LinkedHashMap to build in some additional
smarts that don't consume as much memory as a second map. If the
alternate way your users will query is predictable. The cost will be
in slighty increased access time, but much less than full iteration.
Depends on what is more precious, time or memory. Don't know if "_X"
is the only alternate access or if that is just one of many
possibilities like "nn_X" so I can't elaborate.
BTW the LinkedHashMap (over the HashMap) just gives you the ability to
Iterate in the order you inserted to the map or in the order of Most
Recent Access which also buys you the reverse orders. But that's only
if you are going to Iterate.