问题
Given a Scala collection.SortedMap
and a key k
, what is the most efficient way of getting all keys (or even better, all key-value pairs) greater than k
stored in the sorted map. The returned set of keys should preserve the order of keys.
Of course, I would like to avoid to peruse the whole data structure (i.e. using filterKeys
), and take advantage of the fact that the map is sorted.
I would like to do something like :
val m = collection.SortedMap((1,1) -> "somevalue", (1,2) -> "somevalue",
(1,3) -> "somevalue", (2,1) -> "somevalue", (3,1) -> "somevalue")
m.getKeysGreaterThan((2,1))
// res0: scala.collection.SortedSet[(Int, Int)] = TreeSet((2,1), (3,1))
If you can think of a more appropriate map-like data structure, please suggest it.
回答1:
Try this from the API doc:
m.from((2,1))
Note, that the result is inclusive the key value.
I just checked in Scala 2.10, TreeMap.from
calls from
on RedBlackTree
, which appears to be an efficient implementation (the usual O(log n) for tree-based data-structures).
来源:https://stackoverflow.com/questions/14961566/scala-sortedmap-get-all-keys-greater-than-a-given-key