如何在保持与原始对象的层次结构的同时进行flatMap

时间:2016-04-08 21:30:12

标签: scala apache-spark

case class Rule(a: Int, expression: String, c: String)
val initialVar: Array[Rule] = Array(
  Rule(1, "#25.2.3 Sometext #528.55555.8", "Somename"),
  Rule(1, "#850.152.2.0 Sometext", "Somename")
)

我想要flatMap表达式并得到类似的东西:

val finalVar: Array[(Rule, String)] = Array(
  (Rule(1, "#25.2.3 Sometext #528.55555.8", "Somename"),"25.2.3"),
  (Rule(1, "#25.2.3 Sometext #528.55555.8", "Somename"),"528.55555.8"),
  (Rule(1, "#850.152.2.0 Sometext", "Somename"),"850.152.2.0")
)

我可以重现一些flatMap示例,但仍然无法弄清楚如何使其工作。

1 个答案:

答案 0 :(得分:1)

假设你有一个函数expandRule将你的规则映射到子{4}的子映射,你的flatMap将如下所示:

Seq[String]

这会给你:

case class Rule(a: Int, expression: String, c: String)

val initialVar: Array[Rule] = Array(
  Rule(1, "#25.2.3 Sometext #528.55555.8", "Somename"),
  Rule(1, "#850.152.2.0 Sometext", "Somename")
)

def expandRule(r:Rule):Seq[String] = 
  "#[\\d.]+".r.findAllMatchIn(r.expression).map(_.group(0)).toSeq


initialVar.flatMap(r => expandRule(r).map(r -> _))