I'm implementing a NavigableMap
-implementing LinkedHashMap
in Java. (There don't seem to be many (any?) reasons why LinkedHashMap
doesn't implement NavigableMap
already, but I digress...)
I've written lowerKey()
, lowerEntry()
, higherKey()
, and higherEntry()
by iterating the entrySet()
. I don't see any way in these cases to avoid iterating the entire entrySet()
.
For floorKey()
, floorEntry()
, ceilingKey()
, and ceilingEntry()
, in the case that the key exists, I'd like to avoid the expense of iterating the entrySet()
, considering that I can already get the value with plain-old get()
.
Is there a way to get the Map.Entry
for a particular key, rather than just the value? Thanks.
@Sweeper's comment on his answer got me thinking. The solution I came up with was to maintain a Map
from Key
to Entry
inside my class. That way I have a way of having O(1)
access to the entrySet
. Like so:
Map<K, Map.Entry<K, V>> entryMap = new HashMap<>();
for(final currentEntry : entrySet())
{
entryMap.put(currentEntry.getKey(), currentEntry);
}
I just need to update this Map
every time an operation runs which changes the keySet
. I only need to update the one entry in this Map
that would be affected. That sounds like it wouldn't be very expensive.