Scala SortedMap:获取大于给定键的所有键 [英] Scala SortedMap : Get all keys greater than a given key

查看:34
本文介绍了Scala SortedMap:获取大于给定键的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 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.

推荐答案

从 API 文档中试试这个:

m.from((2,1))

注意,结果包含键值.

我刚刚检查了 Scala 2.10,TreeMap.fromRedBlackTree 上调用了 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆