[Solved] scala how do you group elements in a map


If this is what you’re aiming for:

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

then here is a possibility:

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

0

solved scala how do you group elements in a map