2014-02-26 79 views
3

在:斯卡拉:分流映射大小n列出(地圖最大尺寸3)

Map("k1" -> "v1", "k2" -> "v2", "k3" -> "v3", "k4" -> "v4", "k5" -> "v5", "k6" -> "v6", "k7" -> "v7", "k8" -> "v8", "k9" -> "v9", "k0" -> "v0") 

日期:

List(Map("k1" -> "v1", "k2" -> "v2", "k3" -> "v3), Map("k4" -> "v4", "k5" -> "v5", "k6" -> "v6), Map("k7" -> "v7", "k8" -> "v8", "k9" -> "v9), Map("k0" -> "v0")) 

回答

4
val a = Map("k1" -> "v1", "k2" -> "v2", "k3" -> "v3", "k4" -> "v4", "k5" -> "v5", "k6" -> "v6", "k7" -> "v7", "k8" -> "v8", "k9" -> "v9", "k0" -> "v0") 
a.grouped(3).toList 

這給了你:

res2: List[scala.collection.immutable.Map[String,String]] = List(Map(k2 -> v2, k0 -> v0, k5 -> v5), Map(k9 -> v9, k6 -> v6, k7 -> v7), Map(k1 -> v1, k4 -> v4, k3 -> v3), Map(k8 -> v8)) 

的只有它沒有訂購的東西

爲了讓你可以做這樣的事情的順序:

a.toList.sortBy(_._1).grouped(3).toList.map(_.toMap) 

它給你:

res6: List[scala.collection.immutable.Map[String,String]] = List(Map(k0 -> v0, k1 -> v1, k2 -> v2), Map(k3 -> v3, k4 -> v4, k5 -> v5), Map(k6 -> v6, k7 -> v7, k8 -> v8), Map(k9 -> v9)) 

請注意,您的初始Map不正確排序(最後一個元素是「K0」,但它應該是第一個)。但是,如果你想保持插入順序,並有3分組的地圖列表這個應該工作:

val b = scala.collection.mutable.LinkedHashMap("k1" -> "v1", "k2" -> "v2", "k3" -> "v3", "k4" -> "v4", "k5" -> "v5", "k6" -> "v6", "k7" -> "v7", "k8" -> "v8", "k9" -> "v9", "k0" -> "v0") 
b.toList.grouped(3).toList.map(_.toMap) 

這導致到:

res8: List[scala.collection.immutable.Map[String,String]] = List(Map(k1 -> v1, k2 -> v2, k3 -> v3), Map(k4 -> v4, k5 -> v5, k6 -> v6), Map(k7 -> v7, k8 -> v8, k9 -> v9), Map(k0 -> v0))