简体   繁体   中英

Creating a submap of guava TreeMultimap and efficient iteration of its key-value pairs

I have a TreeMultimap<Integer, String> , which includes duplicate keys also.

I want to get and display the key value pairs which lies within a specific key range, that too with O(logN+m) time complexity, where N is the total number of key value pairs and m is the number of key value pairs within the given range.

I am thinking of converting the TreeMultimap to a SortedMap by using its method asMap() and then creating a submap in the required range.

SortedMap<Integer, Collection<String>> sortedMap = mapList.getTmm().asMap();
return sortedMap.subMap(beg,end);

But, is using asMap() method efficient? How can I display each key-value pair from the object of Collection class with the given time complexity.

Or should I change my approach completely? Please help.

TreeMultimap.asMap() returns a view in O(1) time that operates on the underlying structure (and so is roughly as efficient as working with the Multimap directly). NavigableMap.subMap() similarly returns a view of its underlying structure. This view isn't O(1), since it has to do some searches into the larger map, but it's no worse than what you'd do to manually find the first element and then iterate.

So there is some slight overhead due to the two layers of indirection, but essentially you should expect the same performance as operating on the original data structure directly. Since TreeMultimap is backed by a tree common operations like get and put will be O(log n) and iteration is O(n).

All of that means that iterating over the map returned by someTreeMultimap.asMap().subMap(...) will be O(log n) + O(n) (so, linear), since the submap operation has to search for the first valid entry - from there it just iterates as normal until it reaches the last valid entry. You should have no trouble iterating over the entrySet() of the map returned from subMap() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM