作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
"v1", "k2" -> "v2", "k3" -> "v3", "k4" -> "v4", "k5" -> "v5", "k6" -> "v6", "k7" -> "-6ren">
在:
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"))
最佳答案
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”,但它应该是第一个)。但是如果你想保持插入顺序并将 map 列表按 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))
关于list - Scala:将 map 大小 n 拆分为列表( map 最大大小为 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22038135/
我是一名优秀的程序员,十分优秀!