I have a sorted map, and I'm looking need to find for some key the nearest 'before' and 'after' entries that full-fill some condition.
Entry findAfter(TreeMap map, Key key, Predicate p) {
Entry e = map.higherEntry(key);
while (e!=null && !p.test(e.getValue())
e = map.higherEntry(e.getKey());
return e;
}
This seems inefficient because higherEntry in O(logN). Is there a better way?
I wish TreeMap had map.nextEntry(e) that would work in O(1), but as far as I know, there isn't.
Check this:
map.tailMap(key)gives you aSortedSetview ofmapcontaining all keys greater than or equal tokey.map.tailMap(key).entrySet()would then get you aSet<Map.Entry>of all the entries inmapwhose keys are greater than or equal tokey. According to the javadoc, anIteratorover thatSetreturns the entries in ascending key order.So maybe something like this would work for you:
An iterator over a subset of the keys has got to be a lot closer to O(1) than searching all the keys for each successively higher key.