Scala SortedMap: get all keys greater than a given key

Considering Scala collection.SortedMap

and a key k

, the most efficient way to get all keys (or even better, all key-value pairs) are larger than those k

stored in the sorted map. The returned keyset must preserve the order of the keys. Of course, I would like to avoid having to go through the entire 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 suitable data structure like a map, please suggest one.

+3


source to share


1 answer


Try this from the API doc :

m.from((2,1))

      



Note that the result includes the key value.

I just checked in Scala 2.10, TreeMap.from

calls from

to RedBlackTree

what appears to be efficient (normal O (log n) for tree data structures).

+7


source







All Articles