Scala排序的地图没有方法floor或ceil

St.*_*rio 3 collections scala

我是斯卡拉的新手,但现在我想用它scala.collection.SortedMap来翻新地板.我的意思是这样的:

val m = SortedMap[Long, String]()

def retreiveAndProcess(l: Long) = {
    val floor = // get the floor of l to m
    //do some with floor
}
Run Code Online (Sandbox Code Playgroud)

oxb*_*kes 5

你可以做你想要使用的是什么from,untilto这可能被发现Sorted并报告他们返回远程投影 [1]的集合:

m.to(l).lastKey    //floor

m.from(l).firstKey //ceil
Run Code Online (Sandbox Code Playgroud)

你将不得不检查空虚,因为这将抛出NoSuchElementExceptions.我通常会使用隐式转换添加一些有用的实用程序:

scala> implicit class SortedMapOps[K, V](val m: SortedMap[K, V]) extends AnyVal {
     |   def floor(k: K): Option[(K, V)] = {
     |     val n = m.to(k)
     |     //You could just use n.lastOption here
     |     if (n.isEmpty) None
     |     else Some((n.lastKey, n(n.lastKey)))
     |   }
     | }
defined class SortedMapOps
Run Code Online (Sandbox Code Playgroud)

然后:

scala> SortedMap(1 -> "a", 2 -> "b", 3 -> "c", 5 -> "e")
res2: scala.collection.immutable.SortedMap[Int,String] = Map(1 -> a, 2 -> b, 3 -> c, 5 -> e)

scala> res2.floor(4)
res3: Option[(Int, String)] = Some((3,c))
Run Code Online (Sandbox Code Playgroud)

[1] - 暗示这是O(1),(或至少不是 O(N))