Scala:将地图大小n拆分为列表(地图最大尺寸3)

时间:2014-02-26 10:12:58

标签: list scala map

在:

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"))

1 个答案:

答案 0 :(得分: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))