Search code examples
javacontainerstreemap

Java: iterator from TreeMap entry?


In Java, TreeMap<K,V> uses a RB-tree to store entries, allowing for in-order iteration using map.entrySet().iterator(), while guaranteeing insertion and lookup in log(N) time.

TreeMap also provides methods to find upper and lower bounds for a given key: map.floorEntry(k), map.ceilingEntry(), map.lowerEntry(k) and map.higherEntry(). However, the return value of those is a Map.Entry<K,V> instance and won't directly allow one to visit neighbouring entries. I wanted to visit would-be neighbours of an hypothetical entry given its key.

Is there a way to get an iterator from a TreeMap entry or do what I'm trying to do?

Being more accustomed to C++'s std::map<K,V> class, I'm at a loss here...

NOTE I'm open to a solution using a container library other than java.util's as long as it has a sorted map container with some reasonable time complexity guarantees.


Solution

  • You can take the key of returned Map.Entry<K, V> as a parameter in tailMap(K fromKey) or headMap(K toKey), and iterate the result.