Scala SortedMap : Get all keys greater than a given key

妖精的绣舞 提交于 2020-01-04 04:48:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!