scala如何在地图中对元素进行分组

时间:2018-02-08 21:07:47

标签: scala loops dictionary

我想在列表中使用以下元素对元素进行分组,当且仅当它们以特定的文字字符串结尾时(在这种情况下为chain)。我怎么能做到这一点?

这就是我所拥有的:

val rules_intial = List("r1", "r2", "r3 chain", "r4", "r5 chain", "r6 chain", "r7")

这是我想要获得的:

val rules_final = List("r1", "r2", List("r3 chain", "r4"), List("r5 chain", "r6 chain",  "r7chain", "r8"), "r9", List("r10chain", "r11"))

1 个答案:

答案 0 :(得分:1)

如果这是你的目标:

List(List(r1), List(r2), List(r3 chain, r4), List(r5 chain, r6 chain, r7))

然后这是一种可能性:

val rules = List("r1", "r2", "r3 chain", "r4", "r5 chain", "r6 chain", "r7")

val (groups, last) = rules.foldLeft(List[List[String]](), List[String]()) {
  case ((groups, curGroup), rule) if rule.contains("chain") =>
    (groups, rule :: curGroup)
  case ((groups, Nil), rule) =>
    (List(rule) :: groups, Nil)
  case ((groups, curGroup), rule) =>
    ((rule :: curGroup).reverse :: groups, Nil)
}

val finalGroups = last match {
  case Nil  => groups
  case list => list.reverse :: groups
}

finalGroups.reverse