在排序映射中查找条目的快速方法,其中键是给定数字的最新(小于或等于)

Fast way to find entry in sorted map where key is the latest (lower or equals) to given number

import scala.collection._
val m = CustomizedSortedMap(20150401 -> "A", 20150423 -> "B")
println(m.get(20150402)) // expected "A"
println(m.get(20150422)) // expected "A"
println(m.get(20150423)) // expected "B"
println(m.get(20150424)) // expected "B"

如何在 Scala 中实现这样的自定义 SortedMap?欢迎任何示例或代码片段!谢谢!

通过使用 TreeMap(排序映射)的隐式转换,您可以轻松实现这样的方法:

implicit class CustomizedSortedMap[A, +B](treeMap: TreeMap[A, B]) {
  def getLatest(a: A): Option[B] = {
    treeMap.to(a).lastOption.map(_._2)
  }
}

val m = TreeMap(20150401 -> "A", 20150423 -> "B")
println(m.getLatest(20150402)) // prints "Some(A)"
println(m.getLatest(20150422)) // prints "Some(A)"
println(m.getLatest(20150423)) // prints "Some(B)"
println(m.getLatest(20150424)) // prints "Some(B)"