我是Scala的新手,Scala是否支持固定长度的SortedMap?
我想到的是一张执行以下操作的地图:
严格来说,我不需要对地图进行排序,但如果我们删除最小的密钥,它似乎是必要/可用的
在我开始自己开始之前,我想先问一下。我也将在Samza下运行它,我相信它是单线程的,所以并发性不会成为一个问题。
我在使用scala 2.10
答案 0 :(得分:2)
你可以根据TreeMap
做一些简单的事情,它可以保证按键排列元素:
import scala.collection.immutable.TreeMap
def add[K,V](map: TreeMap[K,V], elem: (K,V), maxSize: Int): TreeMap[K,V] = {
map.takeRight(maxSize - 1) + elem
}
以下是如何使用它:
scala> val m = TreeMap(1 -> "one", 2 -> "two", 3 -> "three")
m: scala.collection.immutable.TreeMap[Int,String] =
Map(1 -> one, 2 -> two, 3 -> three)
scala> val m1 = add(m, 0 -> "zero", 4)
m1: scala.collection.immutable.TreeMap[Int,String] =
Map(0 -> zero, 1 -> one, 2 -> two, 3 -> three)
scala> val m2 = add(m1, 4 -> "four", 4)
m2: scala.collection.immutable.TreeMap[Int,String] =
Map(1 -> one, 2 -> two, 3 -> three, 4 -> four)
scala> val m3 = add(m2, 5 -> "five", 4)
m3: scala.collection.immutable.TreeMap[Int,String] =
Map(2 -> two, 3 -> three, 4 -> four, 5 -> five)
scala> val m4 = add(m3, 0 -> "zero", 4)
m4: scala.collection.immutable.TreeMap[Int,String] =
Map(0 -> zero, 3 -> three, 4 -> four, 5 -> five)
显然,您可以尝试使其更方便地满足您的需求。
答案 1 :(得分:0)
Aleksey的回答非常有帮助。我做了一个小修理
import scala.collection.immutable.TreeMap
def add[K,V](map: TreeMap[K,V], elem: (K,V), maxSize: Int): TreeMap[K,V] = {
(map + elem).takeRight(maxSize - 1)
}
val m = TreeMap(1 -> "one", 2 -> "two", 3 -> "three")
val m1 = add(m, 0 -> "zero", 4)
val m2 = add(m1, 4 -> "four", 4)
val m3 = add(m2, 0 -> "zero", 4)
val m4 = add(m3, 1 -> "one", 4)
val m5 = add(m4, 0 -> "zero", 4)
val m6 = add(m5, 1 -> "one", 4)