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

时间:2015-07-10 09:09:06

标签: scala dictionary collections find sorted

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中实现这样的Customized SortedMap?欢迎任何示例或代码片段!谢谢!

1 个答案:

答案 0 :(得分:2)

通过使用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)"