Java: iterator from TreeMap entry?

Java TreeMap<K,V> uses the RB tree to store records, which allows iteration to be done in order using map.entrySet().iterator() , guaranteeing insert and search in the log (N).

TreeMap also provides methods for finding upper and lower bounds for a given key: map.floorEntry(k) , map.ceilingEntry() , map.lowerEntry(k) and map.higherEntry() . However, the return value is an instance of Map.Entry<K,V> and does not allow direct visits to neighboring records. I wanted to visit the potential neighbors of a hypothetical record with its key key.

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

Being more familiar with the C ++ std::map<K,V> , I don’t understand here ...

NOTE I am open to a solution using a container library other than java.util if it has a sorted container with certain reasonable time guarantees.

+5
source share
1 answer

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

+2
source

Source: https://habr.com/ru/post/1243839/


All Articles