Scala SortedMap:获取大于给定键的所有键 [英] Scala SortedMap : Get all keys greater than a given key
问题描述
给定一个 Scala collection.SortedMap
和一个键 k
,获取所有键的最有效方法是什么(甚至更好,所有键值对) 大于 k
存储在排序映射中.返回的一组键应保留键的顺序.当然,我想避免仔细阅读整个数据结构(即使用 filterKeys
),并利用地图已排序的事实.
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.
我想做类似的事情:
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.
推荐答案
m.from((2,1))
注意,结果包含键值.
我刚刚检查了 Scala 2.10,TreeMap.from
在 RedBlackTree
上调用了 from
,这似乎是一个有效的实现(通常的 O(log n) 用于基于树的数据结构.
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).
这篇关于Scala SortedMap:获取大于给定键的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!